wxt
wxt copied to clipboard
feat: Make injectScript return the created script element
[!NOTE] The patch series in which each PR builds on top of the previous one: #1761, #1762, #1763, #1838 (you are here), #1765.
In case some of the changes are rejected, I will rebase the subsequent PRs on top of main.
Overview
injectScript now returns the created script element. It can be used to e.g. send messages to the script in the form of custom events. The script can add an event listener for them via document.currentScript. An example of bidirectional communication:
// entrypoints/example.content.ts
export default defineContentScript({
matches: ['*://*/*'],
async main() {
const { script } = await injectScript('/example-main-world.js', {
modifyScript(script) {
// Add a listener before the injected script is loaded.
script.addEventListener('from-injected-script', (event) => {
if (event instanceof CustomEvent) {
console.log(`${event.type}:`, event.detail);
}
});
},
});
// Send an event after the injected script is loaded.
script.dispatchEvent(
new CustomEvent('from-content-script', {
detail: 'General Kenobi',
}),
);
},
});
// entrypoints/example-main-world.ts
export default defineUnlistedScript(() => {
const script = document.currentScript;
script?.addEventListener('from-content-script', (event) => {
if (event instanceof CustomEvent) {
console.log(`${event.type}:`, event.detail);
}
});
script?.dispatchEvent(
new CustomEvent('from-injected-script', {
detail: 'Hello there',
}),
);
});
I made injectScript return an object ({ script }) for future extensibility, in particular for returning the result value of the script.
Manual Testing
Create the files in the example above, add the following to wxt.config.ts, observe the event being logged in the console.
export default defineConfig({
manifest: {
web_accessible_resources: [
{
resources: ['example-main-world.js;],
matches: ['*://*/*'],
},
],
},
});
Related Issue
N/A
Deploy Preview for creative-fairy-df92c4 ready!
| Name | Link |
|---|---|
| Latest commit | 4533614cde68244ffe840d418325de2102314dc6 |
| Latest deploy log | https://app.netlify.com/projects/creative-fairy-df92c4/deploys/688fcd6b722428000886bc61 |
| Deploy Preview | https://deploy-preview-1838--creative-fairy-df92c4.netlify.app |
| Preview on mobile | Toggle QR Code...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify project configuration.