onBeforeScript
event of the browser.userScripts
is fired before a user script is executed. It can only be included in the API script, the script registered in "user_scripts"
, where it is used to detect that the custom API methods should be exported to the user script.browser.userScripts.onBeforeScript.addListener(listener) browser.userScripts.onBeforeScript.removeListener(listener) browser.userScripts.onBeforeScript.hasListener(listener)
Events have three functions:
addListener(listener)
removeListener(listener)
listener
argument is the listener to remove.hasListener(listener)
listener
is registered for this event. Returns true
if it is listening, false
otherwise.listener
A function that is called when this event occurs. The function is passed the following arguments:
script
object
that represents the user script that matched a web page. Its properties and methods are as follows:defineGlobals
export
global
object
that provides access to the sandbox for the user script.metadata
scriptMetadata
property set when the user script was registered using userScripts.register
.An example of how the listener might be used:
browser.userScripts.onBeforeScript.addListener(function (script) { script // This is an API object that represents the user script // that is going to be executed. script.metadata // Access the user script metadata (returns the // value of the scriptMetadata property from // the call to userScripts.register. // Export some global properties into the user script sandbox // (this method has to be called synchronously from the // listener, otherwise the user script may have executed). script.defineGlobals({ aGlobalPropertyAccessibleFromUserScriptCode: “prop value”, myCustomAPIMethod(param1, param2) { // Custom methods exported from the API script can use // the WebExtensions APIs available to content scripts. browser.runtime.sendMessage(...); ... return 123; // primitive values can be returned directly ... // Non primitive values have to be exported explicitly // using the export method provided by the script API // object return script.export({ objKey1: { nestedProp: "nestedValue", }, // Explicitly exported objects can also provide methods. objMethod() { ... } }) }, async myAsyncMethod(param1, param2, param2) { // exported methods can also be declared as async }, }); });
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
onBeforeScript |
No |
No |
68
66
|
? |
No |
No |
? |
? |
68 |
? |
? |
? |
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/onBeforeScript