Skip to content

Instantly share code, notes, and snippets.

@richardwestenra
Last active April 20, 2018 18:42
Show Gist options
  • Save richardwestenra/a967af7ec943b8f012ba3e68c1492622 to your computer and use it in GitHub Desktop.
Save richardwestenra/a967af7ec943b8f012ba3e68c1492622 to your computer and use it in GitHub Desktop.
Alternate favicon demo
<html>
<head>
<title>Alternate Favicon switcher</title>
<link id="favicon" rel="shortcut icon" href="https://i.imgur.com/FfxiVKR.png" />
<meta name="theme-color" content="#000000">
</head>
<body>
<h1>Alternate Favicon switcher</h1>
<p>This page demonstrates how a favicon can be swapped out on pages which support and utilize the theme-color meta tag.</p>
<p>Open on <a href="https://bl.ocks.org/richardwestenra/raw/a967af7ec943b8f012ba3e68c1492622/">bl.ocks.org</a> on both a mobile and desktop browser to see it in action.</p>
<script>
const supportingBrowsers = [
{
browser: 'Chrome',
minVersion: 39,
},
{
browser: 'SamsungBrowser',
minVersion: 6,
},
];
const icons = {
light: 'https://i.imgur.com/ykTmYvD.png',
dark: 'https://i.imgur.com/FfxiVKR.png',
};
/**
* Check whether the current browser supports (and implements) theme-color,
* based loosely on https://caniuse.com/#search=theme
* return {Boolean} True if browser supports theme-color, else false
*/
const supportsThemeColor = () => {
// Check for server-side rendering, and for desktop browsers:
if (typeof window === 'undefined' || typeof window.orientation === 'undefined') {
return false;
}
const { userAgent } = window.navigator;
// Check whether the user agent matches any of the supported browsers
const browserMatch = supportingBrowsers.find(({ browser, minVersion }) => {
/* eslint-disable no-useless-escape */
const regex = new RegExp(`${browser}\\/(\\d+)`);
const matches = userAgent.match(regex);
if (!matches) {
return false;
}
const userAgentVersion = Number(matches[1]);
return userAgentVersion >= minVersion;
});
return Boolean(browserMatch);
};
const faviconLink = Array.from(document.getElementsByTagName('link'))
.find(d => d.id === 'favicon' || d.rel.includes('icon'));
if (supportsThemeColor()) {
faviconLink.setAttribute('href', icons.light);
} else {
faviconLink.setAttribute('href', icons.dark);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment