userScripts.onBeforeScript (舊版)
警告:這是已棄用的 userScripts API 的文件。它在 Manifest V2 的 Firefox 中可用。有關在 Manifest V3 中支援使用者指令碼的功能,請參閱新的 userScripts API。
browser.userScripts API 的 onBeforeScript 事件會在使用者指令碼執行之前觸發。它只能包含在 API 指令碼中,即註冊在 "user_scripts" 中的指令碼,用於檢測自定義 API 方法是否應匯出到使用者指令碼。
語法
js
browser.userScripts.onBeforeScript.addListener(listener)
browser.userScripts.onBeforeScript.removeListener(listener)
browser.userScripts.onBeforeScript.hasListener(listener)
事件有三個函式
addListener(listener)-
向此事件新增監聽器。
removeListener(listener)-
停止監聽此事件。
listener引數是要移除的監聽器。 hasListener(listener)-
檢查
listener是否已為此事件註冊。如果正在監聽,則返回true,否則返回false。
addListener 語法
引數
監聽器-
此事件發生時呼叫的函式。該函式會傳遞以下引數:
script-
一個代表與網頁匹配的使用者指令碼的
物件。它的屬性和方法如下:defineGlobals-
一個方法,用於匯出一個包含可在使用者指令碼沙箱中全域性訪問的屬性和方法的物件。此方法必須同步呼叫,以確保使用者指令碼尚未執行。
export-
一個方法,用於將值轉換為使用者指令碼程式碼可以訪問的值。此方法用於匯出到使用者指令碼的 API 方法中,以返回或解析非原始值。匯出的物件還可以提供使用者指令碼程式碼可以訪問和呼叫的方法。
global-
一個提供使用者指令碼沙箱訪問許可權的
物件。 metadata(元資料)-
使用
userScripts.register註冊使用者指令碼時設定的scriptMetadata屬性。
示例
偵聽器可能如何使用的示例
js
browser.userScripts.onBeforeScript.addListener((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, param3) {
// exported methods can also be declared as async
},
});
});
瀏覽器相容性
載入中…