Skip to content

feat: Add manipulateScript option to injectScript #1762

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 2 commits into
base: main
Choose a base branch
from

Conversation

ion1
Copy link

@ion1 ion1 commented Jun 19, 2025

Note

This PR builds on top of #1761 at the moment. In case it is not accepted, I will rebase this on top of main.

Overview

manipulateScript enables the the manipulation of the script element just before it is added to the DOM.

It can be useful for e.g. passing data to the script via the dataset property (which can be accessed by the script via
document.currentScript), as shown in the example:

// entrypoints/example.content.ts
export default defineContentScript({
  matches: ['*://*/*'],
  async main() {
    await injectScript('/example-main-world.js', {
      manipulateScript(script) {
        script.dataset['greeting'] = 'Hello there';
      },
    });
  },
});
// entrypoints/example-main-world.ts
export default defineUnlistedScript(() => {
  console.log(document.currentScript?.dataset['greeting']);
});

It can also be used to change script.async/script.defer or setting up event listeners for communication through the script element.

Manual Testing

It can be tested as shown in the example above.

Related Issue

#1755 proposes a higher level (and potentially type-checked) API for passing an object to the script.

ion1 added 2 commits June 19, 2025 16:16
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.
It enables the manipulation of the script element just before it is
added to the DOM.

It can be useful for e.g. passing data to the script via the `dataset`
property (which can be accessed by the script via
`document.currentScript`).
@ion1 ion1 requested review from aklinker1 and Timeraa as code owners June 19, 2025 15:47
Copy link

netlify bot commented Jun 19, 2025

Deploy Preview for creative-fairy-df92c4 ready!

Name Link
🔨 Latest commit 55c59d4
🔍 Latest deploy log https://app.netlify.com/projects/creative-fairy-df92c4/deploys/68543131e5b55d0008fb0c4c
😎 Deploy Preview https://deploy-preview-1762--creative-fairy-df92c4.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant