繁体   English   中英

Firefox插件的“ tabs.onUpdated”如何工作?

[英]How does the “tabs.onUpdated” for Firefox Addons work?

我正在玩Firefox插件,因此对我来说它大部分是新的。 另外,我没有太多的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,您必须存储对相应选项卡的引用。

更新:您可以将第二个参数extraParametersaddListenerbrowser.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*/] }) extraParameters browser.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*/] })

匹配模式文档

感谢您添加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';

每当该选项卡的URL更改时,就会将True (从后台脚本中的onUpdated处理程序)打印到浏览器控制台(而不是开发人员工具控制台!)。 与您的网址格式匹配的页面将显示红色边框;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM