Firefox Addons 的 "tabs.onUpdated" 是如何工作的?

How does the "tabs.onUpdated" for Firefox Addons work?

我正在使用 Firefox Addons,所以它对我来说大多是新的。此外,我没有太多的 JS 知识。因此,在文档 (https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated) 上,我找到了“tabs.onUpdated”事件,它完全符合我的需要(如果具有特定 url 的选项卡发生变化,我需要一个运行函数的事件url)。所以我复制了示例并通读了页面,但无法正常工作。有人可以帮助我吗?

谢谢阿基拉


代码:

manifest.json:

{

  "manifest_version": 2,
  "name": "Testing Add-on",
  "version": "1.0",

  "description": "Test Add-on",

  "icons": {
    "48": "icons/border-48.png"
  },

  "content_scripts": [
    {
      "matches": ["*://developer.mozilla.org/*"],
      "js": ["content_script.js"]
    }
  ],

  "permissions": ["tabs", "<all_urls>"]
}

content_script.js:(只是为了测试脚本是否有效)

console.log("Before");
browser.tabs.onUpdated.addListener((tabId, changed) => {
    if (changed.url) {
        console.log("True");
    }
})
console.log("After");
    browser.tabs.onUpdated.addListener((tabId, changed) => {
        if (changed.url) {
            // URL of tab has changed
        }
    })

因此,为了让您判断具有特定 URL 的选项卡是否已更改其 URL,您必须存储对相应选项卡的引用。

更新: 您可以将第二个参数 extraParameters 传递给 addListenerbrowser.tabs.onUpdated.addListener(callback, { urls: [/*array of match patters. Fire the event only for tabs whose current url property matches any one of the patterns*/] })

match patterns docs

感谢您添加 manifest.json。 在浏览器控制台(使用 Ctrl+Shift+J 或 web-ext run --bc 打开的控制台)中,您可以看到以下错误消息:

TypeError: browser.tabs is undefined

这是因为您在内容脚本中使用了 browser.tabs,而您应该在后台脚本中使用它。

将以下内容添加到您的清单文件中:

    "background": {
        "scripts": ["background_script.js"]
    }

-> background_script.js 包含您的 content_script.js 的内容。 现在将您的内容脚本留空。这是将被注入匹配给定 URL 模式的页面的脚本。

您可以在 content_script.js 中写入如下内容(仅用于测试): document.body.style.border = '5px solid red';

True(来自后台脚本中的 onUpdated 处理程序)将在该选项卡的 URL 更改时打印到浏览器控制台(而不是开发人员工具控制台!) . 与您的 URL 模式匹配的页面将显示红色边框;)