Changing website favicon dynamically

前端 未结 15 1330
温柔的废话
温柔的废话 2020-11-22 02:17

I have a web application that\'s branded according to the user that\'s currently logged in. I\'d like to change the favicon of the page to be the logo of the private label,

15条回答
  •  攒了一身酷
    2020-11-22 02:32

    Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different demo of code that works in IE11 too. The following example might not work in Safari or Internet Explorer.

    /*!
     * Dynamically changing favicons with JavaScript
     * Works in all A-grade browsers except Safari and Internet Explorer
     * Demo: http://mathiasbynens.be/demo/dynamic-favicons
     */
    
    // HTML5™, baby! http://mathiasbynens.be/notes/document-head
    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);
    }
    

    You would then use it as follows:

    var btn = document.getElementsByTagName('button')[0];
    btn.onclick = function() {
     changeFavicon('http://www.google.com/favicon.ico');
    };
    

    Fork away or view a demo.

提交回复
热议问题