Javascript chrome.storage.local.get 和 set
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13872542/
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
chrome.storage.local.get and set
提问by Sudarshan
I'm trying to use chrome.storage.localin my extension, and it doesn't seem to work. I used localStoragebut realized that I can't use it in content scripts over multiple pages.
我正在尝试chrome.storage.local在我的扩展程序中使用它,但它似乎不起作用。我使用过localStorage但意识到我不能在多个页面的内容脚本中使用它。
So, this is what I've come up with:
所以,这就是我想出的:
function save()
{
var channels = $("#channels").val();
var keywords = $("#keywords").val();
chrome.storage.local.set({'channels': channels});
chrome.storage.local.set({'keywords': keywords});
}
I do believe I'm doing the save()right, but the problem comes up in load():
我确实相信我做save()对了,但问题出现在load():
function load()
{
var channels = "";
chrome.storage.local.get('channels', function(result){
channels = result;
alert(result);
});
var keywords = "";
chrome.storage.local.get('keywords', function(result){
keywords = result;
alert(result);
});
$("#channels").val(channels);
$("#keywords").val(keywords);
}
When the alerts trigger, it prints out [object Object]. Why is that? What am I doing wrong? I looked at the documentation/examples, but I can't seem to pinpoint the problem.
当警报触发时,它会打印出[object Object]. 这是为什么?我究竟做错了什么?我查看了文档/示例,但似乎无法确定问题所在。
回答by Sudarshan
This code works for me:
这段代码对我有用:
function load() {
var channels = "";
var keywords = "";
chrome.storage.local.get('channels', function (result) {
channels = result.channels;
alert(result.channels);
$("#channels").val(channels);
});
}
Chrome.storage.local.get()returns an object with items in their key-value mappings, so you have to use the index of the key in your search pattern.
Chrome.storage.local.get()返回一个包含键值映射中项目的对象,因此您必须在搜索模式中使用键的索引。
IMP:
进口商:
Thanks to Rob for identifying: Chrome.storage.local.get()is asynchronous, you should modify your code to ensure they work after callback() is successful.
感谢 Rob 指出:Chrome.storage.local.get()是异步的,您应该修改代码以确保它们在 callback() 成功后工作。
Let me know if you need more information.
如果您需要更多信息,请与我们联系。
回答by 7zark7
debug or use
调试或使用
alert(JSON.stringify(result));
for more details as to what you are getting back
有关您返回的内容的更多详细信息
回答by Mdbook
The "result" value you are using is an object that contains the storage value, to get the value you have to use result.keywords, which will get the value of the keywords. EX:
您正在使用的“结果”值是一个包含存储值的对象,要获取您必须使用result.keywords的值,它将获取关键字的值。前任:
function load(){
chrome.storage.local.get('keywords', function(result){
var keywords = result.keywords;
alert(keywords);
});
chrome.storage.local.get('channels', function(result){
var channels = result.channels;
alert(channels);
});
}

