Skip to content

Commit 4617287

Browse files
committed
feat: Add waitUntilLoaded to injectScript
1 parent 55c59d4 commit 4617287

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

docs/guide/essentials/content-scripts.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -583,7 +583,13 @@ export default defineConfig({
583583

584584
`injectScript` works by creating a `script` element on the page pointing to your script. This loads the script into the page's context so it runs in the main world.
585585

586-
`injectScript` returns a promise, that when resolved, means the script has been evaluated by the browser and you can start communicating with it.
586+
`injectScript` returns a promise, that when resolved, means the `script` element has been added to the DOM. To additionally wait until the script has been evaluated by the browser and you can start communicating with it, set `waitUntilLoaded: true` in the options.
587+
588+
```ts
589+
await injectScript('/example-main-world.js', {
590+
waitUntilLoaded: true,
591+
});
592+
```
587593

588594
:::warning Warning: `run_at` Caveat
589595
For MV3, `injectScript` is synchronous and the injected script will be evaluated at the same time as your the content script's `run_at`.

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

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

35+
let loadedPromise: Promise<void> | undefined = undefined;
36+
if (options?.waitUntilLoaded) {
37+
loadedPromise = new Promise((resolve, reject) => {
38+
script.onload = () => {
39+
resolve();
40+
};
41+
script.onerror = () => {
42+
reject(new Error(`Failed to load script: ${script.src}`));
43+
};
44+
});
45+
}
46+
3547
await options?.manipulateScript?.(script);
3648

3749
(document.head ?? document.documentElement).append(script);
3850

3951
if (!options?.keepInDom) {
4052
script.remove();
4153
}
54+
55+
await loadedPromise;
4256
}
4357

4458
export interface InjectScriptOptions {
@@ -47,6 +61,12 @@ export interface InjectScriptOptions {
4761
* injected. To disable this behavior, set this flag to true.
4862
*/
4963
keepInDom?: boolean;
64+
/**
65+
* By default, `injectScript` returns as soon as the `script` element has been
66+
* added to the DOM. To additionally wait until the browser has loaded (or
67+
* failed to load) the script, set this flag to true.
68+
*/
69+
waitUntilLoaded?: boolean;
5070
/**
5171
* Manipulate the script element just before it is added to the DOM.
5272
*

0 commit comments

Comments
 (0)