【问题标题】:Chrome Extension: Replacing FaviconsChrome 扩展程序:替换网站图标
【发布时间】: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


【解决方案1】:

您需要使用消息传递将 url 从 background.js 传递到 contentscript.js 背景.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {url: url}, function(response) {});  
});

在内容脚本上,您需要替换 url,如

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.url)
      {
       var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = url;
    document.getElementsByTagName('head')[0].appendChild(link);
    }
  });

【讨论】:

  • 谢谢!我尝试使用您的代码,它确实替换了 favicon,尽管我必须删除 document.getElementsByTagName('head')[0].appendChild(link) 才能使其工作。不知道为什么。
  • 按照这个想法,我尝试使用 chrome.runtime.getURL("/img/red-circle-16.png") 将网站图标替换为我的扩展程序中的图像。虽然被替换的 url 是有效的 url,但它不会替换页面上的 favicon。
  • DOM 中可以有多个 favicon 链接标签。通过检查 DOM 并在新选项卡中打开 url 确保 url 有效。我在一些网站上尝试了这段代码,它正确地替换了 favicon。
  • 啊,明白了!但是,当我使用 chrome.runtime.getURL 时仍然存在问题。我确实检查并测试了 url,它确实有效。 runtime.getURL 不起作用是否还有其他原因?
  • 你能贴出代码让我弄清楚它有什么问题吗?
猜你喜欢
  • 2021-03-21
  • 2021-07-09
  • 2012-05-26
  • 2017-10-29
  • 2022-11-01
  • 2017-08-10
  • 2018-03-09
  • 2013-05-31
  • 1970-01-01
相关资源
最近更新 更多