简体   繁体   English

如何修复TypeError:在chrome / firefox web扩展中未定义browser.storage?

[英]How to fix TypeError: browser.storage is undefined in chrome/firefox web extension?

Note - this question is based off of this question (although it's not necessary to read the previous question): How to set value of textarea in different HTML file? 注意 - 这个问题是基于这个问题(虽然没有必要阅读上一个问题): 如何在不同的HTML文件中设置textarea的值?

I have the following code, which is supposed to add a value into the local storage of firefox/chrome and then change the extension's UI (the code will differ slightly based upon which browser is being used, as of now, the code is for a extension in firefox): 我有以下代码,它应该在firefox / chrome的本地存储中添加一个值,然后更改扩展的UI(代码将根据使用的浏览器略有不同,截至目前,代码是为了在Firefox中扩展):

function createSummaryBox(summary) {
    console.log("Setting textarea content to: " + summary);
    const currentSummary = {
        currentSummary: summary
    }
    browser.storage.local.set(currentSummary);
    window.location.href = '../summary_page/summary_page.html';
}

However, I get the following error whenever this function is called: 但是,每当调用此函数时,我都会收到以下错误:

ReferenceError: browser.storage is not defined ReferenceError:未定义browser.storage

How can I fix this error? 我该如何解决这个错误? I read through the MDN documentation on this method, so I'm not sure what I'm missing. 我阅读了关于这种方法的MDN文档,所以我不确定我缺少什么。

as comments suggest, you need to declare permission. 如评论所示,您需要声明权限。
In manifest.json add: manifest.json添加:

"permissions": [
    "storage"
],

or add it to any existing permissions: 或将其添加到任何现有权限:

"permissions": [
  "activeTab",
  "storage"
],

Mozilla doc page Mozilla doc页面
Chrome doc page Chrome文档页面

Storage API can be used in content scripts. Storage API可用于内容脚本。
Don't get confused, it's not an issue here, as it is in another Question linked in comments as possible duplicate, which it's not. 不要混淆,这不是问题,因为它在另一个问题中被链接在评论中可能重复,但事实并非如此。

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

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