Toggling dark mode manually via javascript
Building upon my previous explorations, I wanted to let people without an OS-wide dark-mode toggle try it out themselves directly.
For that, we use the styleSheets.cssRules browser API.
Try it! toggle dark/light
function toggleDark() {
let stylesheets = document.styleSheets;
for (let sheet of stylesheets) {
try {
ruleList = sheet.cssRules;
if (ruleList == undefined) {
continue;
}
} catch (e) {
// Catch CORS denials and skip stylesheet
continue;
}
let dark = "(prefers-color-scheme: dark)"
let light = "(prefers-color-scheme: light)"
for (let rule of ruleList) {
/* type 4 == CSSMediaRule */
if (rule.type !== 4) {
continue;
}
let text = rule.media.mediaText;
if (text.slice(0, 22) == "(prefers-color-scheme:") {
rule.media.mediaText == dark ?
rule.media.mediaText = light :
rule.media.mediaText = dark
}
}
}
}
Caveat: If testing this on local file://
URIs, CORS will
bite you, either on Chrome or FF.
On FF, at least you can remedy this by setting privacy.file_unique_origin=false
in about:config
.
See CVE-2019-11730.
For Firefox, you'd be better off installing the website-dark-mode-switcher add-on instead.