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
    },
  });
});

浏览器兼容性

另见