feat: Add modifyScript option to injectScript (#1762)
Co-authored-by: Aaron <aaronklinker1@gmail.com>
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user