2016 年更新:
谷歌浏览器发布存储API:https://developer.chrome.com/docs/extensions/reference/storage/
与其他 Chrome API 一样,它非常易于使用,您可以在 Chrome 中的任何页面上下文中使用它。
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
要使用它,请确保在清单中定义它:
"permissions": [
"storage"
],
有“remove”、“clear”、“getBytesInUse”和一个事件监听器来监听改变的存储“onChanged”
使用原生 localStorage(2011 年的旧回复)
内容脚本在网页上下文中运行,而不是在扩展页面中运行。因此,如果您从 contentscript 访问 localStorage,它将是来自该网页的存储,而不是扩展页面存储。
现在,要让您的内容脚本读取您的扩展存储(您在选项页面中设置它们的位置),您需要使用扩展 message passing。
您要做的第一件事是告诉您的内容脚本向您的扩展发送请求以获取一些数据,而该数据可以是您的扩展本地存储:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
您可以围绕它创建一个 API,将通用 localStorage 数据获取到您的内容脚本,或者获取整个 localStorage 数组。
我希望这有助于解决您的问题。
为了花哨和通用......
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});