Skip to content

Commit de58942

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 55c59d4 commit de58942

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

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

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

35+
const loadedPromise = makeLoadedPromise(script);
36+
3537
await options?.manipulateScript?.(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+
script.onload = () => {
51+
resolve();
52+
};
53+
script.onerror = () => {
54+
reject(new Error(`Failed to load script: ${script.src}`));
55+
};
56+
});
4257
}
4358

4459
export interface InjectScriptOptions {

0 commit comments

Comments
 (0)