feat: Add modifyScript option to injectScript (#1762)

Co-authored-by: Aaron <aaronklinker1@gmail.com>
This commit is contained in:
Johan Kiviniemi
2025-12-16 23:47:40 +02:00
committed by GitHub
parent 938c25cab4
commit 6f84d45960
2 changed files with 33 additions and 0 deletions
+23
View File
@@ -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 `<script>` block. This means for MV2, your script is injected asynchronously and it will not be evaluated at the same time as your content script's `run_at`.
:::
The `script` element can be modified just before it is added to the DOM by using the `modifyScript` option. This 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`. An example:
```ts
// entrypoints/example.content.ts
export default defineContentScript({
matches: ['*://*/*'],
async main() {
await injectScript('/example-main-world.js', {
modifyScript(script) {
script.dataset['greeting'] = 'Hello there';
},
});
},
});
```
```ts
// entrypoints/example-main-world.ts
export default defineUnlistedScript(() => {
console.log(document.currentScript?.dataset['greeting']);
});
```
## Mounting UI to dynamic element
In many cases, you may need to mount a UI to a DOM element that does not exist at the time the web page is initially loaded. To handle this, use the `autoMount` API to automatically mount the UI when the target element appears dynamically and unmount it when the element disappears. In WXT, the `anchor` option is used to target the element, enabling automatic mounting and unmounting based on its appearance and removal.
+10
View File
@@ -32,6 +32,8 @@ export async function injectScript(
script.src = url;
}
await options?.modifyScript?.(script);
(document.head ?? document.documentElement).append(script);
if (!options?.keepInDom) {
@@ -45,4 +47,12 @@ export interface InjectScriptOptions {
* injected. To disable this behavior, set this flag to true.
*/
keepInDom?: boolean;
/**
* Modify 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`).
*/
modifyScript?: (script: HTMLScriptElement) => Promise<void> | void;
}