簡體   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