javascript 未捕获的类型错误:无法读取 chrome 扩展中未定义的属性“本地”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15113562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:32:44  来源:igfitidea点击:

Uncaught TypeError: Cannot read property 'local' of undefined in chrome extension

javascriptgoogle-chrome-extensionlocal-storagegoogle-chrome-storage

提问by Milind Anantwar

I have written a Chrome extension. I cannot use localStorage.setItemand localStorage.getItemfor storing and retrieving because background and browser action runs in different environment [as seen here].

我写了一个 Chrome 扩展。我无法使用 localStorage.setItemlocalStorage.getItem进行存储和检索,因为后台和浏览器操作在不同的环境中运行 [如此处所见]。

So I decided to use the Chrome storage API:

所以我决定使用 Chrome 存储 API:

var storage = chrome.storage.local;
var myTestVar = 'somevar';
var obj = {};
obj[myTestVar] = $("#somevar").val();
storage.set(obj);

which produced the following error:

这产生了以下错误:

Uncaught TypeError: Cannot read property 'local' of undefined

未捕获的类型错误:无法读取未定义的属性“本地”

What am I doing wrong?

我究竟做错了什么?

回答by Rob W

Make sure that all necessary permissionshave been declared in the manifest file. "storage", in your case.

确保在清单文件中声明了所有必要的权限"storage",在你的情况下。

In general, the following steps should fix the problem of apparently undefined Chrome APIs:

一般来说,以下步骤应该可以解决明显未定义的 Chrome API 的问题:

  1. Read the documentation of the API you're using and get yourself familiar with the prerequisites, usually manifest permissions (e.g. chrome.storage#manifest).
  2. Check if your (user's) Chrome version supports the API, by looking at What's new.
  3. Check if the script is running in the right context. Most APIs are only available to the extension's process. (the chrome.storageAPI can also be used in content script though)
  4. Otherwise, resort to your usual debugging skills: Typos, variable shadowing, ...
  1. 阅读您正在使用的 API 的文档并熟悉先决条件,通常是清单权限(例如chrome.storage#manifest)。
  2. 通过查看What's new 来检查您(用户的)Chrome 版本是否支持该 API 。
  3. 检查脚本是否在正确的上下文中运行。大多数 API 仅可用于扩展进程。(chrome.storageAPI 也可以在内容脚本中使用)
  4. 否则,请使用您通常的调试技巧:错别字、变量阴影、...