Skip to content

feat: add awaitExecution option to injectScript utility #1789

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions packages/wxt/src/utils/inject-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,32 @@ export async function injectScript(
script.src = url;
}

if (!options?.keepInDom) {
script.onload = () => script.remove();
if (
options?.awaitExecution &&
browser.runtime.getManifest().manifest_version === 3
) {
// For MV3 with awaitExecution, return a promise that resolves when script loads
return new Promise<void>((resolve, reject) => {
script.onload = () => {
if (!options?.keepInDom) {
script.remove();
}
resolve();
};
script.onerror = () => {
if (!options?.keepInDom) {
script.remove();
}
reject(new Error(`Failed to load script: ${path}`));
};
(document.head ?? document.documentElement).append(script);
});
} else {
if (!options?.keepInDom) {
script.onload = () => script.remove();
}
(document.head ?? document.documentElement).append(script);
}

(document.head ?? document.documentElement).append(script);
}

export interface InjectScriptOptions {
Expand All @@ -45,4 +66,9 @@ export interface InjectScriptOptions {
* injected. To disable this behavior, set this flag to true.
*/
keepInDom?: boolean;
/**
* If true, the function will return a promise that resolves when the script
* has finished loading. Only supported in MV3.
*/
awaitExecution?: boolean;
}
Loading