Skip to content

Commit d0b11fd

Browse files
committed
More resilient CSS patching.
1 parent 3827ec2 commit d0b11fd

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/common/themes.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
*/
2020

2121
{
22+
const PARENT_CLASS = "__NoScript_Theme__";
2223
let patchSheet = s => {
24+
const PARENT_SELECTOR = `.${PARENT_CLASS}`;
2325
let rules = s.cssRules;
2426
for (let j = 0, len = rules.length; j < len; j++) {
2527
let rule = rules[j];
@@ -28,7 +30,10 @@
2830
}
2931
if (rule.conditionText !== "(prefers-color-scheme: light)") continue;
3032
for (let r of rule.cssRules) {
31-
s.insertRule(`${r.selectorText}[data-theme="light"] {${r.style.cssText}}`, j);
33+
let {selectorText} = r;
34+
if (selectorText.includes("[data-theme=") || !selectorText.startsWith(PARENT_SELECTOR)) continue;
35+
selectorText = selectorText.replace(PARENT_SELECTOR, `${PARENT_SELECTOR}[data-theme="light"]`);
36+
s.insertRule(`${selectorText} {${r.style.cssText}}`, j);
3237
}
3338
return true;
3439
}
@@ -37,7 +42,12 @@
3742

3843
let patchAll = () => {
3944
for (let s of document.styleSheets) {
40-
if (patchSheet(s)) return true;
45+
try {
46+
if (patchSheet(s)) return true;
47+
} catch (e) {
48+
// cross-site stylesheet?
49+
console.error(e, s.href);
50+
}
4151
}
4252
return false;
4353
}
@@ -54,7 +64,7 @@
5464

5565

5666
let root = document.documentElement;
57-
root.classList.add("__NoScript_Theme__");
67+
root.classList.add(PARENT_CLASS);
5868

5969
const VINTAGE = "vintageTheme";
6070

0 commit comments

Comments
 (0)