chrome.storage set\get clarification

假装没事ソ 提交于 2019-12-01 02:44:54

问题


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.

My save function is (looked at how Currently did 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(){});

Printing the storage in the console results in a better output:

undefined

shai

Still not sure what this undefined is...


Update 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.

Any suggestions?


回答1:


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.

In addition:

chrome.storage.sync is an asynchronous 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:

"permissions": [ "storage" ],



来源:https://stackoverflow.com/questions/14613403/chrome-storage-set-get-clarification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!