Skip to content

Commit a52b234

Browse files
committed
fix: Make injectScript wait until loaded
The documentation states: > `injectScript` returns a promise, that when resolved, means the script > has been evaluated by the browser and you can start communicating with > it. However, currently `injectScript` returns as soon as the `script` element has been added to the DOM. Make `injectScript` behave according to the documentation.
1 parent e040fb5 commit a52b234

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

packages/wxt/src/utils/inject-script.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,39 @@ export async function injectScript(
3232
script.src = url;
3333
}
3434

35+
const loadedPromise = makeLoadedPromise(script);
36+
3537
await options?.modifyScript?.(script);
3638

3739
(document.head ?? document.documentElement).append(script);
3840

3941
if (!options?.keepInDom) {
4042
script.remove();
4143
}
44+
45+
await loadedPromise;
46+
}
47+
48+
function makeLoadedPromise(script: HTMLScriptElement): Promise<void> {
49+
return new Promise((resolve, reject) => {
50+
const onload = () => {
51+
resolve();
52+
cleanup();
53+
};
54+
55+
const onerror = () => {
56+
reject(new Error(`Failed to load script: ${script.src}`));
57+
cleanup();
58+
};
59+
60+
const cleanup = () => {
61+
script.removeEventListener('load', onload);
62+
script.removeEventListener('error', onerror);
63+
};
64+
65+
script.addEventListener('load', onload);
66+
script.addEventListener('error', onerror);
67+
});
4268
}
4369

4470
export interface InjectScriptOptions {

0 commit comments

Comments
 (0)