We can use prefers-color-scheme: dark to detect if dark mode is activated or not:
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
Is there a way detect if a browser supports dark mode at all? (By "supports dark mode" I mean the browser automatically changes the default background/text colors of web pages).
In CSS, we can force dark mode with
color-scheme: dark;
however, some browsers (Firefox for Android) will ignore it. So I'd like to hide theme selection if dark mode is not available.
My current solution is to switch between dark and light mode and check if default color has changed between the modes:
const hasDarkMode = function()
{
const el = document.createElement("div");
el.style.display = "none";
document.body.appendChild(el);
let color;
/*canvastext - doesn't work in Samsung Internet, initial/unset - doesn't work in Firefox*/
for(let i = 0, c = ["canvastext", "initial", "unset"]; i < c.length; i++ )
{
el.style.color = c[i];
el.style.colorScheme = "dark";
color = getComputedStyle(el).color;
el.style.colorScheme = "light";
color = color != getComputedStyle(el).color;
if (color)
break;
}
document.body.removeChild(el);
return color;
}();
console.log("Dark mode supported:", hasDarkMode);
This might not be the most elegant solution, but it seems to be working.
With comment from @connexo we can also test with:
const hasDarkMode = CSS.supports("color-scheme", "dark");
console.log("Dark mode supported:", hasDarkMode);
@supports (color-scheme: dark)
{
.no-dark-mode
{
display: none;
}
}
<div>Dark mode is <span class="no-dark-mode">not </span>available</div>