Carles Andrés

Passionate Web Developer

QuickTip: Change a Favicon Programatically

Sometimes it’s very useful to manipulate a favicon dynamically from your javascript. It turns out it might be easier than you thought.

A very simple favicon formed by a filled-in circle superimposed with a letter can be achieved in 3 simple steps:

  1. Create the image using the canvas API
  2. Convert the canvas image to a dataURL
  3. Replace the page’s favicon with newly created image (by removing the previous and adding the new one)

The following code achieves exactly that purpose.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 var replaceFavicon = function(src){
     document.head || (document.head = document.getElementsByTagName('head')[0]);
     var link = document.createElement('link');
     var 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);
}

 var createFavicon = function(color, letter){
    color = color || 'black';
    letter = letter || 't';
    var ctx;
    var strData;

    // These 100px is an arbitrary size, good enough for changing the small
    // icon in a browser's tab which is usually far smaller
    var canvas = document.createElement('canvas');
    canvas.setAttribute('width', 100);
    canvas.setAttribute('height', 100);


    ctx = canvas.getContext('2d');
    ctx.arc( 50,50,50,0,2*Math.PI );
    ctx.fillStyle = color;
    ctx.fill();

    // Draw letter
    ctx.fillStyle = 'white';
    ctx.font = 'bold normal 90px monospace';
    ctx.fillText(letter, 25, 75);

    strData = canvas.toDataURL('image/png', 1.0);
    replaceFavicon(strData);
};


 createFavicon('#ddd');

You can see this code in action at https://carlesandres.github.io/change_favicon/ .

And you can make contributions to the code in https://github.com/carlesandres/change_favicon .

My web application Textmarkr.com makes use of that same code to help identify the currently open file among all other browser tabs using the same app.

Your comments are more than welcome. :)

Comments