Skip to content

Commit c1ebd08

Browse files
committed
fix #1709 and simplify styleInjector
+ fix potential race conditions in docRootObserver + remove orphaned styles immediately after receiving new styles
1 parent 585da7a commit c1ebd08

File tree

3 files changed

+133
-155
lines changed

3 files changed

+133
-155
lines changed

.types.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ declare interface InjectedStyle {
5858
id: number,
5959
code: string[],
6060
name: string,
61+
/** Added in style-injector */
62+
el?: HTMLStyleElement|CSSStyleSheet;
6163
}
6264

6365
declare interface InjectionConfig {

content/apply.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
let matchUrl = isFrameNoUrl
3131
? parent.location.href.split('#')[0]
3232
: location.href;
33-
let isOrphaned;
33+
let isOrphaned, orphanCleanup;
3434
let offscreen;
3535
// firefox doesn't orphanize content scripts so the old elements stay
3636
if (!CHROME) styleInjector.clearOrphans();
@@ -77,7 +77,7 @@
7777
addEventListener('pageshow', onBFCache);
7878

7979
if (!chrome.tabs) {
80-
dispatchEvent(new Event(chrome.runtime.id));
80+
dispatchEvent(new CustomEvent(chrome.runtime.id, {detail: orphanCleanup = Math.random()}));
8181
addEventListener(chrome.runtime.id, orphanCheck, true);
8282
}
8383

@@ -95,6 +95,10 @@
9595
else data = !isFrameSameOrigin && !isXml && !chrome.tabs && tryCatch(getStylesViaXhr);
9696
// XML in Chrome will be auto-converted to html later, so we can't style it via XHR now
9797
await applyStyles(data);
98+
if (orphanCleanup) {
99+
dispatchEvent(new Event(orphanCleanup));
100+
orphanCleanup = false;
101+
}
98102
}
99103

100104
async function applyStyles(data) {
@@ -104,8 +108,8 @@
104108
Object.assign(own, window[Symbol.for(SYM_ID)] = data);
105109
if (!isFrame && own.cfg.top === '') own.cfg.top = location.origin; // used by child frames via parentStyles
106110
if (!isFrame && own.cfg.dark !== mqDark.matches) mqDark.onchange(mqDark);
107-
if (styleInjector.list.length) await styleInjector.replace(own);
108-
else if (!own.cfg.off) await styleInjector.apply(own);
111+
if (styleInjector.list.length) styleInjector.replace(own);
112+
else if (!own.cfg.off) styleInjector.apply(own);
109113
styleInjector.toggle(!own.cfg.off);
110114
}
111115

@@ -258,7 +262,7 @@
258262
if (offscreen) for (const fn of offscreen) fn();
259263
offscreen = null;
260264
isOrphaned = true;
261-
setTimeout(styleInjector.clear, 1000); // avoiding FOUC
265+
styleInjector.shutdown(evt.detail);
262266
tryCatch(msg.off, applyOnMessage);
263267
}
264268
})();

0 commit comments

Comments
 (0)