From 41833c644da51d05a0c3baeba2d9877b57d42b14 Mon Sep 17 00:00:00 2001 From: Johan Kiviniemi Date: Thu, 19 Jun 2025 12:28:53 +0300 Subject: [PATCH 1/2] feat: Remove script element immediately in injectScript Everything seems to work: the script is executed; onload, onerror handlers do the right thing; document.currentScript invoked by the script returns the detached script element. --- packages/wxt/src/utils/inject-script.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/wxt/src/utils/inject-script.ts b/packages/wxt/src/utils/inject-script.ts index 2043e2da8..833b85266 100644 --- a/packages/wxt/src/utils/inject-script.ts +++ b/packages/wxt/src/utils/inject-script.ts @@ -32,11 +32,11 @@ export async function injectScript( script.src = url; } + (document.head ?? document.documentElement).append(script); + if (!options?.keepInDom) { - script.onload = () => script.remove(); + script.remove(); } - - (document.head ?? document.documentElement).append(script); } export interface InjectScriptOptions { From e040fb5c633624489422fad72ffbb428888bfebe Mon Sep 17 00:00:00 2001 From: Johan Kiviniemi Date: Thu, 19 Jun 2025 13:42:34 +0300 Subject: [PATCH 2/2] feat: Add modifyScript option to injectScript It enables the modification of the script element just before it is added to the DOM. It can be used to e.g. modify `script.async`/`script.defer`, add event listeners to the element, or pass data to the script via `script.dataset` (which can be accessed by the script via `document.currentScript`). --- docs/guide/essentials/content-scripts.md | 23 +++++++++++++++++++++++ packages/wxt/src/utils/inject-script.ts | 10 ++++++++++ 2 files changed, 33 insertions(+) diff --git a/docs/guide/essentials/content-scripts.md b/docs/guide/essentials/content-scripts.md index 3c0c77a93..018a83fb2 100644 --- a/docs/guide/essentials/content-scripts.md +++ b/docs/guide/essentials/content-scripts.md @@ -591,6 +591,29 @@ For MV3, `injectScript` is synchronous and the injected script will be evaluated However for MV2, `injectScript` has to `fetch` the script's text content and create an inline `