我有一个选项页面,用户可以在其中定义某些选项,并将其保存在localStorage中:
现在,我还有一个内容脚本,它需要获取在
页面,但是当我尝试从内容脚本访问localStorage时,它没有从options页面返回值。
我如何让我的内容脚本从localStorage,从选项页面,甚至从背景页面获取值?
发布于 2010-10-15 06:11:23
更新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);
});
要使用它,请确保在清单中定义它:
"permissions": [
"storage"
],
有"remove“、"clear”、"getBytesInUse“的方法,还有一个监听存储"onChanged”更改的事件侦听器。
使用原生localStorage (
2011年的旧回复
)
内容脚本在网页的上下文中运行,而不是在扩展页面的上下文中运行。因此,如果你从你的内容脚本访问localStorage,它将是来自该网页的存储,而不是扩展页面存储。
现在,要让您的内容脚本读取您的扩展存储(在选项页面中对其进行设置),您需要使用扩展
消息传递
..。
您要做的第一件事是告诉您的内容脚本向您的扩展发送一个请求来获取一些数据,这些数据可以是您的扩展localStorage:
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.
});
您可以绕过这个问题来将通用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.
});
发布于 2014-01-12 02:38:27
有时使用它可能会更好
chrome.storage
API。它比localStorage更好,因为你可以:
存储内容脚本中的信息
不需要消息传递
在内容脚本和扩展之间;
将数据存储为JavaScript对象
而不将它们序列化为JSON (
localStorage仅存储字符串
)。
下面是一个简单的代码,演示了chrome.storage的用法。Content script获取访问页面的url和时间戳并存储,popup.js从存储区获取。
内容
_
script.js
(function () {
var visited = window.location.href;
var time = +new Date();
chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
console.log("Just visited",visited)
});
})();
popup.js
(function () {
chrome.storage.onChanged.addListener(function (changes,areaName) {
console.log("New item in storage",changes.visitedPages.newValue);
})
})();
"Changes“在这里是一个对象,它包含给定key的旧值和新值。"AreaName“参数是指存储区域的名称,可以是”local“、”sync“或”managed“。
记得在manifest.json中声明存储权限。
manifest.json
...
"permissions": [
"storage"
],
...
发布于 2012-07-19 13:30:07
另一种选择是使用chromestorage API。这允许通过可选的跨会话同步来存储用户数据。
一个缺点是它是异步的。
https://developer.chrome.com/extensions/storage.html
https://stackoverflow.com/questions/3937000
复制相似问题