On this page
Example of browser tab with favicon and badge on it

Add a badge to the browser tab favicon using JavaScript

In this tutorial, we will look at how to add a badge to the current favicon in the tab using JavaScript.

Adding a badge to the favicon using JavaScript can be done by updating the image specified by the <link> element with a new icon image.

This method involves JavaScript and creating an in-memory canvas element, applying the favicon image, drawing the badge shape and text on top, and then updating the <link> element’s href attribute with the final composite of the canvas element’s image data as a Base64 encoded string.

Example final code with updated favicon

<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAABs9JREFUWEeNlwtwVNUZx3/f3d08IQkbkbSYCNNUSYAQxgCpoEPEagE77VCUtmpBR0wTHiN2YEahg02nnaGDKDpYdLS0FG0tMx1LOzjaQmRdxTgh2oqYMlQaLC3vQMJjN7n3nvbcu3f37kt6Zndm9zz/5//9v8cRkk0AlfiX8Xv23iCTSqoZHq7DUHNApgE3ilCubAyEM82Dfzux7MQr1szBDysqzIu13rYidCubvQg7wgf4yH+eoBD0x2ne4W5P8t+y6ERs+SHQjLKuQ4xAahMoUENs6NvM4lN/8Hfn/i1sGdXNSkFsfYI+J3G6oNGkIAArIqMxpRXFOhEp9I95AKvjJ/nN4dXUX/n0atfwA+qx4K7RB/iPPt67froh2iINKNmGyBQgkMGJM7fIHmLPxw9Rd+XTPDdP49GZ4/QoEJGeih41TRS2CyA5V+DhyAwC8jugJtmtr58BdfPRDdx/+o/p5vJDCYbANNNMm4ZU2BLuZnn6tq1vT8EwdoGqyWdQTVrjpU+c22c2KS2jtGM7wRlfRYpKUAP9XP5pK0N/2ZljO+d6DSkA2uaWsRtFU87DNXUGlBQY/Pjo0yz5lybJbd4mI7btJzi5GfPDKObB9ylc+H0HyMA9E7H+cSiLRVH8TJI0t0c7UDzu2jy7zZ04iqU3j+G6cCHXr5pB6NihFAAFKhRi1P44arCf8y2VzljBouWUrnmW2K83Etu82hW5Z073Qt0u+NaueozhD/SazKNDAWHt3GrWz6t2hxT0T5PURt4CI0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KO80NKbKkjaoj8C1qIkgKRCUU24kIVTKwmXBqksDSW+QQqDQsAQdL2gW8AwMG2bUwMm27tO8uqBVD5wOHeqUWeqhZIOts7s8BzTGZAlkdGq0NiN5CnJMoygD3YAGB4AcTRyecjGTpY+OS13gKA9l2dvPZ0C4M1bvm+yWIE/KV0RJ5KMO5TPm68mjcwYIn2EuItnZh709nRfBv4XWeu708He6S9QksfkKM8deIl+zXIuT0qsP4ay72brre+ndOZ7GaU9zdoiDUqMl1BM9YrUPM8MHzs5WHIBWSi0wB9gq755ektnwM+29zRDrQMj6R3O8oyb5jWQYgjhSYnZT6ltrs2zAeTpTPrBQ/vqJBRYr/TjVBiLIugHkIMZE9RxlLyLPdSBdjXfyzNzfs6clSTCG12oAlIRqVHBwASUzEHUdBT6CV6JYCOcw+YIQhdi7MWml7Nf+Yyd4hYBn6Ph/wLqaYwhmbBrUQAAAABJRU5ErkJggg==" sizes="any">

Browser, tab and added badge to the current favicon
Browser tab with added dynamically badge to the current favicon

Understanding what a favicon is

A favicon is a little icon that is used to represent a website. It is typically represented through the image in .ico, .png, .gif, .jpeg and .svg format and displayed with the page URL on browser tabs, bookmark bars, history, and search results. The term favicon is an abbreviation for favorite icon.

Use cases for the badge in the favicon

Possible use cases:

  • Chat, email, and social apps, to indicate that new messages have come or to display the amount of unread items.
  • To notify the user that a long-running task has been completed.
  • Games, to indicate that a player action is necessary (for example, when it is the player’s turn in chess).
  • E-commerce platforms to show cart item counts or promotional notifications.

Adding a badge to your browser tab favicon with JavaScript

Let’s add a simple notification badge to the current favicon using JavaScript.

Add a notification badge to the favicon – JavaScript version.
function addBadge(favicon) {
  const faviconSize = 32;
  const canvas = document.createElement('canvas');

  canvas.width = faviconSize;
  canvas.height = faviconSize;

  const context = canvas.getContext('2d');
  const img = new Image();
  img.crossOrigin = 'anonymous'; // Attempt CORS if needed

  const createBadge = () => {
    // Clear canvas before drawing
    context.clearRect(0, 0, faviconSize, faviconSize);
    context.drawImage(img, 0, 0, faviconSize, faviconSize);

    // Badge properties
    const badgeValue = 6;
    const badgeRadius = faviconSize / 3;
    const badgeX = canvas.width - badgeRadius;
    const badgeY = badgeRadius;

    context.beginPath();
    context.arc(badgeX, badgeY, badgeRadius, 0, 2 * Math.PI);
    context.fillStyle = '#e30';
    context.fill();

    context.font = 'bold 15px Arial, sans-serif';
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillStyle = '#fff';
    context.fillText(badgeValue, badgeX, badgeY);

    favicon.href = canvas.toDataURL('image/png');
  };

  img.addEventListener('load', createBadge);
  img.addEventListener('error', () => {
    console.warn('Failed to load favicon for badge creation');
  });

  img.src = favicon.href;
}

document.querySelectorAll('link[rel="shortcut icon"], link[rel="icon"]').forEach(addBadge);

This code creates a canvas element and draws the favicon image and a red circle with the number 6 on it. Then it sets the favicon href to the data URL of the canvas. It applies the function to all link elements with rel attribute of shortcut icon or icon.

You can change the parameters of the badge, such as the number, font size, font family, badge background color, text align, and text baseline.

Important considerations:
  • Cross-Origin Resource Sharing (CORS): If the favicon is hosted on a different domain, canvas.toDataURL() will throw a security error due to canvas tainting. The crossOrigin = 'anonymous' attribute attempts to load the image with CORS, but the server must also send appropriate CORS headers.
  • SVG favicons: While modern browsers support drawing SVG favicons to canvas, some older browsers may have limitations. Test thoroughly across your target browsers.
  • Accessibility: Dynamic favicon changes should not be the only notification method. Always provide alternative notifications for accessibility, as users with cognitive disabilities or those using screen readers may not notice favicon changes.
Please keep in mind that changing the favicon dynamically using JavaScript may not be supported by all browsers. It is advised that you test your solution across many browsers to verify compatibility. Specific browser notes:
  • Chrome and Edge: Generally support dynamic favicons well.
  • Firefox: May have issues with certain favicon updates in specific versions.
  • Safari: Intentionally prohibits dynamic favicon modifications (see below).
  • Mobile browsers: Often don’t display favicons at all.

I can’t change the favicon with JavaScript in Safari

Safari browser intentionally prohibits the use of dynamic modifications or animations on the favicon. This means that you cannot use JavaScript or any other method to change or animate the favicon in Safari.

We (Apple) intentionally do not want the ability to script favicons.

This restriction is in place to maintain a consistent user experience and prevent potential abuse or misuse of the favicon feature. While other browsers may allow dynamic modifications or animations on the favicon, Safari has chosen to restrict this functionality.

Please note that this restriction specifically applies to the favicon, which is the small icon displayed in the browser tab. It does not necessarily apply to other dynamic modifications or animations on websites or web applications viewed in Safari.

Taking it to the next level with an enhanced version

Provided code is a very simple example, but it has some limitations. The badge does not adjust to the number of digits, and there’s no caching mechanism to prevent redundant favicon requests.

Let’s take our favicon game to the next level with our more advanced version. Let’s create a dynamic favicon that changes based on dynamic factors and set some requirements.

  • The badge must automatically adjust its size to the number of digits.
  • The badge is added using a link HTML element, but there might be a rel="shortcut icon" or rel="icon". We need to handle both.
  • There might be more than one version of the favicon. We need to handle all versions.

    Example:
    <link rel="icon" href="https://www.sitelint.com/favicon.ico" type="image/x-icon" sizes="any">
    and
    <link rel="icon" href="https://www.sitelint.com/favicon.svg" type="image/svg+xml">.

  • The above code will trigger an HTML request for a favicon every time a new badge is generated. Let’s then avoid that by implementing a caching mechanism.
  • Changing the color of the badge.
  • Ability to remove a badge. This basically brings back the original favicon.

Implementing favicon caching

To avoid redundant HTTP requests, implement a simple caching mechanism for favicon images:

const faviconCache = new Map();

function getFavicon(url) {
  if (faviconCache.has(url)) {
    return Promise.resolve(faviconCache.get(url));
  }
  
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => {
      faviconCache.set(url, img);
      resolve(img);
    };
    img.onerror = reject;
    img.src = url;
  });
}

Framework integration

This favicon badge technique can be easily integrated with popular JavaScript frameworks:

  • React: create a custom hook useFaviconBadge() that manages the badge state and updates the favicon in useEffect().
  • Vue: implement as a composable or directive that watches reactive badge values.
  • Angular: create a service with methods to set and clear badges, injectable across components.

Real-world examples

Popular applications that use favicon badges include:

  • WhatsApp web: shows unread message count.
  • X (formerly Twitter): displays notification count.
  • Gmail: indicates unread email count.
  • Trello: shows board notifications.

You can experiment with different parameters in example Add a badge to the browser tab favicon using JavaScript.

Alternative approaches

While canvas-based favicon generation is powerful, consider these alternatives:

  • Pre-generated favicons: Create multiple favicon versions server-side and swap between them using JavaScript.
  • SVG favicons with JavaScript: For browsers that support SVG favicons, you can dynamically update SVG content without canvas.
  • Emoji favicons: Use emoji characters as favicons for simple badge indicators where detailed graphics aren’t required.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Audit and debug pages with browser extension

Boost your website’s quality by auditing your page with SiteLint, a chromium-based extension that improves accessibility, quality, technical SEO, and provides easy-to-understand reports to help you prioritize and fix issues.