Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 2, 2025 04:09
Show Gist options
  • Save westc/119663d702434732d4ea6ba0943e2e2e to your computer and use it in GitHub Desktop.
Save westc/119663d702434732d4ea6ba0943e2e2e to your computer and use it in GitHub Desktop.
Sets a single character (eg. a unicode emoji as the favicon for the page.
/**
* Sets the character stored in FAVICON_CHARACTER as the favicon for this page.
*/
addEventListener('DOMContentLoaded', () => {
// The single character that will appear as the favicon for this page.
const FAVICON_CHARACTER = '\u{1F510}';
// Remove all `<link>` elements that are for icons.
document.querySelectorAll("link[rel~='icon']").forEach(el => el.remove());
// The canvas that will be used to generate the image that will show as the
// favicon.
const size = 64;
const canvas = document.createElement('canvas');
canvas.width = canvas.height = size;
const ctx = canvas.getContext('2d');
// Draw the emoji character on the canvas.
ctx.font = `${size * 9 / 10}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(FAVICON_CHARACTER, size / 2, size / 2);
// Add the favicon to the page's head.
const link = document.createElement('link');
link.rel = 'icon';
link.type = 'image/png';
link.href = canvas.toDataURL('image/png');
document.head.appendChild(link);
});
@westc
Copy link
Author

westc commented Aug 2, 2025

Learn how to test this code out here by watching this short YouTube tutorial:
https://youtu.be/IgLmjYv4gC4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment