Search code examples
javascriptfaviconbookmarklet

How do you make a bookmarklet change page icon?


Before I begin, this is NOT a duplicate. To explain my goal, I want a bookmark that, when clicked, changes the page icon WITHOUT loading a new tab. Other similar questions gave your bookmarklet an icon, but nothing accomplished what I wanted.

Here is the code I have right now:

data:text/html; charset=utf-8, <html><link rel="shortcut icon" href="http://link-to-my-icon.info/favicon.ico"></html>

It works, but it changes my tab. I want to keep the tab open, but edit the HTML to change the page icon. I've tried using

javascript: document.write(<link rel="shortcut icon" href="http://transparent-favicon.info/favicon.ico">);

as well, but it does absolutely nothing, while my first attempt at least changes the icon.

Any help would be greatly appreciated, thanks.


Solution

  • Checkout this gist and the demo.

    //source: https://gist.github.com/mathiasbynens/428626
    
    document.head || (document.head = document.getElementsByTagName('head')[0]);
    
    function changeFavicon(src) {
     var link = document.createElement('link'),
         oldLink = document.getElementById('dynamic-favicon');
     link.id = 'dynamic-favicon';
     link.rel = 'shortcut icon';
     link.href = src;
     if (oldLink) {
      document.head.removeChild(oldLink);
     }
     document.head.appendChild(link);
    }