Getting `Uncaught (in promise) Error: Missing host permission for the tab` in background script of firefox extension

Getting `Uncaught (in promise) Error: Missing host permission for the tab` in background script of firefox extension

这是我的后台脚本;

/**
 * CSS to hide everything on the page,
 */
const hidePage = `body > : {
    display: none;
  }`;


/**
 * When a tab is loaded, check if the plugin is on. If the plugin is on, check if the url matches the page.
 * If it does, block it
 */
browser.tabs.onActivated.addListener(function (activeInfo) {
    browser.storage.local.get("onOff")
        .then((result) => {
            if (Object.entries(result).length === 0 || !result.onOff.value) {
                return;
            }
            browser.tabs.query({ currentWindow: true, active: true }).then((tabs) => {
                let tab = tabs[0];
                console.log(tab.url);
                browser.tabs.insertCSS({code: hidePage})
            }, console.error)
        });
});

这是我的 manifest.json

{

    "manifest_version": 2,
    "name": "Beastify",
    "version": "1.0",
  
    "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
    "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
    "icons": {
      "48": "icons/beasts-48.png"
    },
  
    "permissions": [
      "tabs",
      "activeTab",
      "storage"
    ],
  
    "browser_action": {
      "default_icon": "icons/beasts-32.png",
      "default_title": "BlockIt",
      "default_popup": "popup/blockit.html"
    },

    "background": {
      "scripts": ["background_scripts/blocker.js"]
    },
  
    "web_accessible_resources": [
      "beasts/frog.jpg",
      "beasts/turtle.jpg",
      "beasts/snake.jpg"
    ]
  
  }

那里有些多余的东西,因为我正在从 Firefox extension tutorial.

构建我的附加组件

导致 Uncaught (in promise) Error: Missing host permission for the tab

browser.tabs.insertCSS({code: hidePage})

第 23 行 blocker.js

我相信我确实拥有从该后台脚本插入 css 的正确权限,因此我无法弄清楚为什么会出现此错误。我还尝试执行一个内容脚本而不是 运行 上面那行抛出错误,但失败并出现相同的错误。

activeTab 仅当用户按照 WebExtensions and Chrome extensions 的文档中所述显式调用您的扩展程序时才有效。显然,它的名字具有很强的误导性:它应该是 activeTabWhenInvoked.

为了在不事先与您的扩展程序交互的情况下访问任何选项卡,您必须在 manifest.json:

中添加广泛的主机权限
  "permissions": ["<all_urls>"],

现在不需要 activeTab,但对于 86 版以上的 Firefox,您可能仍想保留 tabs 权限,请参阅 note in the documentation

P.S。最好在 onOff 为 false 时完全删除侦听器,这样扩展不会 运行 白费。您可以通过为 onActivated 侦听器使用全局命名函数并通过 browser.storage.onChanged 事件观察对 onOff 的更改来实现。