Search code examples
javascriptgoogle-chrome-extensionfavicon

Chrome Extension: Replacing Favicons


In my chrome extension, I'm trying to find and then replace a site's favicon with a different favicon. I'm able to find the site's favicon url, but I am stuck on how to actually replace it.

I tried using chrome.tabs.query and using it's property of favIconUrl but I couldn't get it to work, so I then used a method of getting the site's favicon by going to https://www.google.com/s2/favicons?domain=exampledomain.com. This does get the url for the favicon, but I am confused on how to proceed to replace the favicon.

EDIT: included more code

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);
    }
})

Solution

  • You need to pass url from background.js to contentscript.js using message passing like background.js

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

    and on Content script you need to replace url like

    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);
        }
      });