正在获取"未捕获(承诺中)错误:firefox扩展的后台脚本中缺少选项卡的主机权限"



这是我的背景脚本;

/**
* 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扩展教程中构建插件的。

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

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

blocker.js的第23行

我相信我确实有正确的权限从这个后台脚本插入css,所以我不知道为什么会出现这个错误。我还尝试执行一个内容脚本,而不是运行上面引发错误的行,但由于同样的错误而失败。

activeTab只有在用户显式调用您的扩展时才能工作(如WebExtensions和Chrome扩展文档中所述(。显然,它的名字极具误导性:它应该是activeTabWhenInvoked

为了在没有事先与扩展交互的情况下访问任何选项卡,您必须在manifest.json:中添加广泛的主机权限

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

现在不需要activeTab,但您可能仍然希望为86以上的Firefox保留tabs权限,请参阅文档中的注释。

第页。S.当onOff为false时,最好完全删除侦听器,这样扩展就不会徒劳地运行。您可以为onActivated侦听器使用全局命名函数,并通过browser.storage.onChanged事件观察对onOff的更改。

最新更新