javascript chrome.storage set\get 说明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14613403/
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 set\get clarification
提问by Shaihi
I want to save information in my extenstion. I use Chrome.storage.sync
to do that, however when I read right after saving I am unable to rightly retrieve the value. Probably doing something stupid....
I tried clearing the local storage with chrome.storage.sync.clear
but that did not help.
我想在我的扩展中保存信息。我曾经Chrome.storage.sync
这样做过,但是当我在保存后立即阅读时,我无法正确检索该值。可能做了一些愚蠢的事情......我尝试清除本地存储,chrome.storage.sync.clear
但这没有帮助。
My save function is (looked at how Currentlydid it):
我的保存功能是(看看目前是如何做到的):
save: function (type, key, data) {
Storage.storageOption(type).set({key:data}, function () {
console.log("saved data");
});
load: function (type, key) {
Storage.storageOption(type).get(key, function (object) {
console.log("read : " +object);
return object[key];
})}
and calling it as:
并将其称为:
Storage.save("", 'path',username);
console.log(Storage.load("",'path'));
Which results in this:
结果如下:
saved data
undefined
read : [object Object]
保存的数据
不明确的
阅读:[对象对象]
Update:
更新:
OK, apparently there is a problem in how I pass the object's key-value pair because when I call it like this:
chrome.storage.sync.set({'path':username}, function(){});
好的,显然我如何传递对象的键值对存在问题,因为当我这样调用它时:
chrome.storage.sync.set({'path':username}, function(){});
Printing the storage in the console results in a better output:
在控制台中打印存储会产生更好的输出:
undefined
shai
不明确的
晒
Still not sure what this undefined is...
仍然不确定这个未定义是什么......
Update 2:
更新 2:
After successfully writing to the storage, trying to read it when document ready is fired. Using the following code:
成功写入存储后,尝试在文档就绪时读取它。使用以下代码:
var dbdata = chrome.storage.sync.get("path",function(object){
return object['path'];
});
However, the function's body is not executed, although the documentation says it will be run in any case and will set lastError in case of an error.
然而,函数的主体并没有被执行,尽管文档说它在任何情况下都会运行,并且会在出现错误时设置 lastError 。
Any suggestions?
有什么建议?
回答by Pascal Belloncle
The returning value from the function you pass to chrome.storage.sync does not do what you expect. The value is only available within the callback. It does not end up in dbdata
.
您传递给 chrome.storage.sync 的函数的返回值不符合您的预期。该值仅在回调中可用。它不会以dbdata
.
In addition:
此外:
chrome.storage.sync
is an asynchronous API.
chrome.storage.sync
是一个异步 API。
You have to wait for it to complete before you can retrieve the data.
您必须等待它完成才能检索数据。
chrome.storage.sync.set({'value': 12}, function() {
chrome.storage.sync.get("value", function(data) {
console.log("data", data);
});
});
and the output is:
输出是:
data Object {value: 12}
manifest.json must contain:
manifest.json 必须包含:
"permissions": [ "storage" ],
“权限”:[“存储”],