我有一个选项页面,用户可以在其中定义某些选项并将其保存在 localStorage 中:options.html
现在,我还有一个内容脚本,需要获取在 options.html
页面中定义的选项,但是当我尝试从内容脚本访问 localStorage 时,它没有从选项页面返回值。
如何让我的内容脚本从 localStorage、选项页面甚至后台页面获取值?
最佳答案
2016 年更新:
Google Chrome 发布了存储 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);
});
要使用它,请确保在 list 中定义它:
"permissions": [
"storage"
],
有“remove”、“clear”、“getBytesInUse”等方法,还有一个事件监听器来监听更改的存储“onChanged”
使用 native localStorage(2011 年的旧回复)
内容脚本在网页上下文中运行,而不是在扩展页面中运行。因此,如果您从内容脚本访问 localStorage,则它将是该网页的存储,而不是扩展页面的存储。
现在,要让您的内容脚本读取扩展存储(您在选项页面中设置它们),您需要使用扩展 message passing .
您要做的第一件事是告诉您的内容脚本向您的扩展程序发送请求以获取一些数据,并且该数据可以是您的扩展程序 localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
背景.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);
});
背景.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
关于google-chrome-extension - Chrome 扩展程序 : accessing localStorage in content script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937000/