More resilient CSS patching.

This commit is contained in:
hackademix 2022-03-23 10:57:29 +01:00
parent 3827ec27c8
commit d0b11fddec
1 changed files with 13 additions and 3 deletions

View File

@ -19,7 +19,9 @@
*/ */
{ {
const PARENT_CLASS = "__NoScript_Theme__";
let patchSheet = s => { let patchSheet = s => {
const PARENT_SELECTOR = `.${PARENT_CLASS}`;
let rules = s.cssRules; let rules = s.cssRules;
for (let j = 0, len = rules.length; j < len; j++) { for (let j = 0, len = rules.length; j < len; j++) {
let rule = rules[j]; let rule = rules[j];
@ -28,7 +30,10 @@
} }
if (rule.conditionText !== "(prefers-color-scheme: light)") continue; if (rule.conditionText !== "(prefers-color-scheme: light)") continue;
for (let r of rule.cssRules) { for (let r of rule.cssRules) {
s.insertRule(`${r.selectorText}[data-theme="light"] {${r.style.cssText}}`, j); let {selectorText} = r;
if (selectorText.includes("[data-theme=") || !selectorText.startsWith(PARENT_SELECTOR)) continue;
selectorText = selectorText.replace(PARENT_SELECTOR, `${PARENT_SELECTOR}[data-theme="light"]`);
s.insertRule(`${selectorText} {${r.style.cssText}}`, j);
} }
return true; return true;
} }
@ -37,7 +42,12 @@
let patchAll = () => { let patchAll = () => {
for (let s of document.styleSheets) { for (let s of document.styleSheets) {
try {
if (patchSheet(s)) return true; if (patchSheet(s)) return true;
} catch (e) {
// cross-site stylesheet?
console.error(e, s.href);
}
} }
return false; return false;
} }
@ -54,7 +64,7 @@
let root = document.documentElement; let root = document.documentElement;
root.classList.add("__NoScript_Theme__"); root.classList.add(PARENT_CLASS);
const VINTAGE = "vintageTheme"; const VINTAGE = "vintageTheme";