Changing website favicon dynamically

前端 未结 15 1310
温柔的废话
温柔的废话 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:23

    Here's some code I use to add dynamic favicon support to Opera, Firefox and Chrome. I couldn't get IE or Safari working though. Basically Chrome allows dynamic favicons, but it only updates them when the page's location (or an iframe etc in it) changes as far as I can tell:

    var IE = navigator.userAgent.indexOf("MSIE")!=-1
    var favicon = {
        change: function(iconURL) {
            if (arguments.length == 2) {
                document.title = optionalDocTitle}
            this.addLink(iconURL, "icon")
            this.addLink(iconURL, "shortcut icon")
    
            // Google Chrome HACK - whenever an IFrame changes location 
            // (even to about:blank), it updates the favicon for some reason
            // It doesn't work on Safari at all though :-(
            if (!IE) { // Disable the IE "click" sound
                if (!window.__IFrame) {
                    __IFrame = document.createElement('iframe')
                    var s = __IFrame.style
                    s.height = s.width = s.left = s.top = s.border = 0
                    s.position = 'absolute'
                    s.visibility = 'hidden'
                    document.body.appendChild(__IFrame)}
                __IFrame.src = 'about:blank'}},
    
        addLink: function(iconURL, relValue) {
            var link = document.createElement("link")
            link.type = "image/x-icon"
            link.rel = relValue
            link.href = iconURL
            this.removeLinkIfExists(relValue)
            this.docHead.appendChild(link)},
    
        removeLinkIfExists: function(relValue) {
            var links = this.docHead.getElementsByTagName("link");
            for (var i=0; i

    To change favicons, just go favicon.change("ICON URL") using the above.

    (credits to http://softwareas.com/dynamic-favicons for the code I based this on.)

提交回复
热议问题