【发布时间】:2018-07-25 17:59:38
【问题描述】:
在我的 chrome 扩展程序中,我试图找到一个网站的图标并将其替换为不同的图标。我能够找到该网站的网站图标 url,但我被困在如何实际替换它上。
我尝试使用chrome.tabs.query 并使用它的favIconUrl 属性,但我无法让它工作,因此我使用了一种方法来获取网站的图标,即转到https://www.google.com/s2/favicons?domain=exampledomain.com。这确实获得了 favicon 的 url,但我对如何继续替换 favicon 感到困惑。
编辑:包含更多代码
background.js
chrome.commands.onCommand.addListener(colorTabs);
function colorTabs(command)
{
var url = "https://www.google.com/s2/favicons?domain=";
var addFaviconUrl;
if ("left-key-toggle-feature" == command)
{
chrome.tabs.query({currentWindow: true, active: true}, function(tabs)
{
/* favicon url */
addFaviconUrl = tabs[0].url;
url += addFaviconUrl;
chrome.tabs.sendMessage(tabs[0].id, {url: url}, function(response) {});
})
}
};
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
if (request.url)
{
var link = document.querySelector("link[rel*='shortcut icon']") || document.createElement("link");
link.type = "image/x-icon";
link.rel = "shortcut icon";
link.href = chrome.runtime.getURL("img/red-circle-16.png"); // not working
//link.href = "https://www.google.com/s2/favicons?domain=google.com"; // works!
document.getElementsByTagName("head").appendChild(link);
}
})
【问题讨论】:
-
您需要执行一个 content 脚本,它将替换页面中用于 favicon 的
<link>元素。
标签: javascript google-chrome-extension favicon