Skip to content

Instantly share code, notes, and snippets.

@NGR-NP
Created January 11, 2024 18:46
Show Gist options
  • Save NGR-NP/200cb30c70baaae733d43cac8c3bfc3e to your computer and use it in GitHub Desktop.
Save NGR-NP/200cb30c70baaae733d43cac8c3bfc3e to your computer and use it in GitHub Desktop.
dynamic favicon icon similar to WhatsApp's notification badge
function updateFavicon(notificationsCount) {
if (notificationsCount === 0) {
// No notifications, so just exit and don't update the favicon
return;
}
const canvas = document.createElement('canvas');
canvas.width = 16;
canvas.height = 16;
const ctx = canvas.getContext('2d');
const image = new Image();
image.src = '/favicon.ico';
image.onload = () => {
ctx.drawImage(image, 0, 0);
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(canvas.width - 5, 5, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '8px sans-serif';
ctx.fillText(notificationsCount.toString(), canvas.width - 5, 5);
const link = document.querySelector("link[rel~='icon']") || document.createElement('link');
link.rel = 'icon';
link.href = canvas.toDataURL('image/x-icon');
const existingIcons = document.querySelectorAll("link[rel~='icon']");
existingIcons.forEach(icon => document.head.removeChild(icon));
document.head.appendChild(link);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment