Closed EmiliaPaz closed 3 months ago
What would be the function's arguments? Does it accept a "code" parameter? Does it accept a "runAt" parameter? Is it going to be affected by the CSP of the target page? Will the script run in the global scope or a local scope? (i.e. can the script create global variables?)
Hopefully you don't mind me posting the answers to these questions which I found while researching the PR as it's something I'll use in my extensions as well:
code
runAt
Thanks @Getfree for taking a look at the proposal. And special thanks to @tophf for providing answers. These are mostly correct, but I am expanding them more:
What would be the function's arguments?
userScripts.execute(injection: UserScriptInjection)
. You can see it in more detail on the API Schema
section in the proposal.
Does it accept a "code" parameter?
Yes, injection has a User Script API ScriptSource
parameter which includes code.
Does it accept a "runAt" parameter?
No. By default in run at document_idle
but can be set to injectImmediately
Is it going to be affected by the CSP of the target page?
Depends on the world it's injected to. User script can be registered/executed in the USER_SCRIPT
or MAIN
world. The USER_SCRIPT
world is an execution environment specific to user scripts and is exempt from the page's CSP. The MAIN
world is the execution environment shared with the host page's JavaScript, and thus follows the page's CSP.
@tophf , not sure I follow your answer here. Extension can decide the world in which a script is registered. Script registered in MAIN
world will follow the page's CSP, and when registered in USER_SCRIPT
world will follow the extension CSP or a customized one For example:
script1
is registered in MAIN
world and it does not have access to eval()
since page csp dissallows eval()
. script2
is registered in USER_SCRIPT
world. Extension can configure the USER_SCRIPT
world to allow eval()
, does script gets access to eval()
Will the script run in the global scope or a local scope? (i.e. can the script create global variables?)
It runs on the global scope.
@tophf , not sure I follow your answer here.
I was referring to the existing problem in the currently used workaround for MV3 to run arbitrary code by creating a script element inside code that already runs in the MAIN world - this workaround didn't work with a strict CSP of the page. With the new userScripts API the code will run regardless of the CSP of the page (it still affects the artifacts created by this code). I think this is an important info that could be used for an explicit clarification in the documentation.
This PR has been approved and is ready to merge (I don't have the power to do so :) )
Proposal for adding
<browser>.userScripts.execute()
API to allow extensions to inject user scripts programmatically into web contents.