Hi all,
I'm excited to share two additions to the User Scripts API - one which is available behind a flag in Chrome Canary, and one which is available in Chrome 133 stable starting this week.
New method: userScripts.execute
Following the addition of the User Scripts API in Manifest V3, we heard from many developers that they often need to inject a script based on a user action. This was not easy to do with the existing API which required that all scripts were registered ahead of time and injected into new pages.
Together with the WebExtensions Community Group, and with help from engineers at Firefox, Safari and Edge, we designed a new `
userScripts.execute()` method that can run a script immediately on the specified target.
We'd love to hear your feedback before this ships by default - you can try it out by starting Chrome Canary with the `--enable-features=ApiUserScriptsExecute` flag.
You can call the API as follows:
```
chrome.userScripts.execute({
target: { tabId:
tab.id },
js: [{ code: "alert('hi')" }]
});
```
Find the full API described in the
WECG proposal.
Multiple user script world support
When a non-extension script runs in a page, it runs in the "MAIN" world. Extension content scripts are run in the "ISOLATED" world which is isolated from other scripts and extensions. This means code on a web page cannot (unintentionally, or maliciously) change global values that the content script will access. With the introduction of the User Scripts API, we introduced a third user script specific "USER_SCRIPT" world. This allows user scripts to be isolated from both content scripts and main world scripts.
The new “USER_SCRIPT” world was an improvement over Manifest V2, but individual user scripts still shared the same world. To make it possible to isolate individual user scripts, starting in Chrome 133, the `
worldId` parameter can be used to run each user script in a unique world. This isolates user scripts from each other, and prevents one user script from interfering with a different one.
You can also use this parameter when setting configuration for a world:
```
chrome.userScripts.configureWorld({
csp: "",
messaging: true,
// You can now specify a world ID.
worldId: "example"
});
```
To access or reset this configuration, we've added new `
getWorldConfigurations()` and `
resetWorldConfiguration()` methods.
We worked on these changes in the WebExtensions Community Group - you can find the proposal
here.
These changes are available and shipping by default in Chrome 133.
As always, please do let us know if you have any feedback. We're excited to keep bringing you these changes and are always looking to make improvements where we can.
Thanks,
Oliver on behalf of Chrome Extensions DevRel