views:

2966

answers:

8

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, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?

I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?

+11  A: 

An arcade game in a favicon:

http://www.p01.org/releases/DHTML_contests/files/DEFENDER_of_the_favicon/

Corey Trager
However, be careful because that method isn't working on IE
paulgreg
+3  A: 

The favicon is declared in the head tag with something like:
<link rel="shortcut icon" type="image/ico" href="favicon.ico">

You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.

Jeff Sheldon
IIRC, however, some browsers (I'm looking in your direction, IE) don't really respect this sometimes.
Matthew Schinckel
(I found I had better results just having the icon file in the right location, rather than the explicit link).
Matthew Schinckel
+10  A: 

Why not?

function() {
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.stackoverflow.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
}();

Firefox should be cool with it.

keparo
I'm thinking this is close to what I'm looking for, but how would I get the appropriate HREF from the database. I suppose I'll have to do a server lookup from javascript, but I don't want it to get too complicated. Thanks for the tip.
rwmnau
Sure, you can always look them up from a database or a filesystem. If there are only a few, you could simply hard code an array of strings.
keparo
Since this doesn’t work in IE anyway, you can remove `shortcut` from the `rel` attribute. [`shortcut` is an invalid IE-proprietary link relation!](http://mathiasbynens.be/notes/rel-shortcut-icon)
Mathias Bynens
+3  A: 

If you have the following HTML snippet:

<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

You can change the favicon using Javascript by changing the HREF element on this link, for instance (assuming you're using JQuery):

$("#favicon").attr("href","favicon2.png");

You can also create a Canvas element and set the HREF as a ToDataURL() of the canvas, much like the Favicon Defender does.

fserb
I think you mean `$('#favicon')` instead of `$('favicon')`.
Mathias Bynens
you're right. Fixed.
fserb
A: 

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

staticsan
A: 

if you're using PHP, just have the href equal to a PHP variable that you've set up per user.

If you're not putting the favicon like http://www.example.com/favicon.ico (where it is in the root directory), it might be a good idea to play with .htaccess (if you're using Apache) to redirect any of those requests to the right file.

Look at your logs, if there anything like mine (before I added a redirector) there were many 404's looking for /favicon.ico

alex
+1  A: 

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<links.length; i++) {
            var link = links[i]
            if (link.type == "image/x-icon" && link.rel == relValue) {
                this.docHead.removeChild(link)
                return}}}, // Assuming only one match at most.

    docHead: document.getElementsByTagName("head")[0]}

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.)

David Morrissey
+3  A: 

Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Still fails in Safari and Internet Explorer though.

/*!
 * 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];

// Browser sniffing :`(
if (/Chrome/.test(navigator.userAgent)) {
 var isChrome = 1,
     iframe = document.createElement('iframe');
 iframe.src = 'about:blank';
 iframe.style.display = 'none';
 document.body.appendChild(iframe);
};

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);
 if (isChrome) {
  iframe.src += '';
 };
};

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.

Mathias Bynens