38

I tried to figure it out looking at the source code but I couldn't figure it out.

I would like to know how to make a dynamic favicon with a count like Gmail does.

enter image description here

Any idea on how to do this?

Loktar
  • 34,764
  • 7
  • 90
  • 104
Santiago
  • 2,405
  • 6
  • 31
  • 43
  • 1
    Note that Chrome's dynamic favicon implementation is buggy and uses too much CPU. See http://code.google.com/p/chromium/issues/detail?id=121333 – brillout Apr 30 '12 at 17:59

1 Answers1

60

You can make an image with the canvas element, and then just replace the current favicon. Check out the following link for a good explanation on it. Reference

Code is from the above reference.

Markup

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

JS

  (function () {
    var canvas = document.createElement('canvas'),
        ctx,
        img = document.createElement('img'),
        link = document.getElementById('favicon').cloneNode(true),
        day = (new Date).getDate() + '';
    
    if (canvas.getContext) {
      canvas.height = canvas.width = 16; // set the size
      ctx = canvas.getContext('2d');
      img.onload = function () { // once the image has loaded
        ctx.drawImage(this, 0, 0);
        ctx.font = 'bold 10px "helvetica", sans-serif';
        ctx.fillStyle = '#F0EEDD';
        if (day.length == 1) day = '0' + day;
        ctx.fillText(day, 2, 12);
        link.href = canvas.toDataURL('image/png');
        document.body.appendChild(link);
      };
      img.src = 'image.png';
    }
    
    })();

Edit

Must have an image set as well.

Community
  • 1
  • 1
Loktar
  • 34,764
  • 7
  • 90
  • 104
  • 2
    This code does more than stated in the first sentence. It is actually drawing on top of "image.png" (the template image source given in the script, not the default in ``) after it is loaded and if the canvas context is available. Also, it is adding a [``](https://developer.mozilla.org/de/docs/Web/HTML/Element/link) element to the body of the document (where it is illegal: `` only), every time the function is run (in this case, once). So I'd try to omit the `cloneNode()` and `appendChild()` and only update the original link href. – handle Aug 20 '16 at 09:31
  • document.getElementById('favicon').href = canvas.toDataURL('image/png'); ? – manthrax Dec 02 '19 at 05:20