Plugin API: a style injected at document start waits for the document root

WebView2 runs document-start scripts before the document has an element, so
injectCSS threw ("reading 'appendChild'") for every CSS feature that was on at
start, e.g. hiding promoted posts, until the next flags delivery restarted it.
Such styles now wait (one MutationObserver for all of them), are attached as
soon as the document has a root, and get their CSP check then; a style cleared
while waiting is never attached.
This commit is contained in:
CRTkafa 2026-10-01 03:39:16 +07:00
parent ba684b477b
commit 95613c9f03
2 changed files with 65 additions and 1 deletions

View file

@ -149,6 +149,25 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
}); });
const styleNodes = new Map<string, HTMLStyleElement>(); const styleNodes = new Map<string, HTMLStyleElement>();
const adoptedFallbacks = new Map<string, RootStyles>(); const adoptedFallbacks = new Map<string, RootStyles>();
// At document start the engine may run us before the document has an element to hold a <style>
// (WebView2: `documentElement` is still null). Such styles wait here and are attached, and their
// CSP check run, as soon as the document has a root.
const pendingStyles = new Set<string>();
let pendingObserver: MutationObserver | null = null;
const attachPending = () => {
const parent = doc.head || doc.documentElement;
if (!parent) return;
pendingObserver?.disconnect();
pendingObserver = null;
const ids = [...pendingStyles];
pendingStyles.clear();
for (const id of ids) {
const node = styleNodes.get(id);
if (!node) continue;
parent.appendChild(node);
api.injectCSS(id, node.textContent ?? '');
}
};
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error); const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
const registry = createCommandRegistry({ target: doc, isTyping: event => isTypingTarget(event.target) || isTypingTarget(doc.activeElement), report }); const registry = createCommandRegistry({ target: doc, isTyping: event => isTypingTarget(event.target) || isTypingTarget(doc.activeElement), report });
const commands: CommandRegistry = Object.freeze({ const commands: CommandRegistry = Object.freeze({
@ -178,11 +197,25 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
const api: CorePluginApi = { const api: CorePluginApi = {
injectCSS(id, css) { injectCSS(id, css) {
let node = styleNodes.get(id); let node = styleNodes.get(id);
if (node && pendingStyles.has(id)) {
node.textContent = css;
return;
}
if (!node?.isConnected) { if (!node?.isConnected) {
node = doc.createElement('style'); node = doc.createElement('style');
node.dataset[site.styleDataKey] = id; node.dataset[site.styleDataKey] = id;
(doc.head || doc.documentElement).appendChild(node);
styleNodes.set(id, node); styleNodes.set(id, node);
const parent = doc.head || doc.documentElement;
if (!parent) {
node.textContent = css;
pendingStyles.add(id);
if (!pendingObserver) {
pendingObserver = new win.MutationObserver(attachPending);
pendingObserver.observe(doc, { childList: true, subtree: true });
}
return;
}
parent.appendChild(node);
} }
node.textContent = css; node.textContent = css;
// A CSP that refuses inline styles leaves the element without a sheet: the same rules as an // A CSP that refuses inline styles leaves the element without a sheet: the same rules as an
@ -198,6 +231,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
} }
}, },
clearCSS(id) { clearCSS(id) {
pendingStyles.delete(id);
styleNodes.get(id)?.remove(); styleNodes.get(id)?.remove();
styleNodes.delete(id); styleNodes.delete(id);
adoptedFallbacks.get(id)?.remove(); adoptedFallbacks.get(id)?.remove();

View file

@ -79,6 +79,36 @@ test('injectCSS marks its style with the site data key and replaces in place', (
assert.equal(styles[0]!.isConnected, false); assert.equal(styles[0]!.isConnected, false);
}); });
test('injectCSS at document start waits for the document root instead of throwing', () => {
const observers: { fire(): void; disconnected: boolean }[] = [];
const { api, doc, win, styles } = fakeEnv();
Object.assign(win, {
MutationObserver: class {
disconnected = false;
callback: () => void;
constructor(callback: () => void) { this.callback = callback; observers.push(this); }
observe() {}
disconnect() { this.disconnected = true; }
fire() { this.callback(); }
},
});
const head = doc.head;
Object.assign(doc, { head: null, documentElement: null });
assert.doesNotThrow(() => api.injectCSS('early', 'a{}'));
api.injectCSS('early', 'b{}');
api.injectCSS('gone', 'c{}');
api.clearCSS('gone');
assert.equal(styles.filter(node => node.isConnected).length, 0);
assert.equal(observers.length, 1, 'one observer for every waiting style');
Object.assign(doc, { head, documentElement: {} });
observers[0]!.fire();
const connected = styles.filter(node => node.isConnected);
assert.equal(connected.length, 1, 'a cleared style is never attached');
assert.equal(connected[0]!.dataset.demoPlugin, 'early');
assert.equal(connected[0]!.textContent, 'b{}', 'the latest text wins');
assert.equal(observers[0]!.disconnected, true);
});
test('onKey skips typing, modifiers and the second key of site chords', () => { test('onKey skips typing, modifiers and the second key of site chords', () => {
const { api, doc } = fakeEnv(); const { api, doc } = fakeEnv();
const keys: string[] = []; const keys: string[] = [];