chrome.storage set\get clarification

Shaihi picture Shaihi · Jan 30, 2013 · Viewed 16.1k times · Source

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?

Answer

Pascal Belloncle picture Pascal Belloncle · Jan 30, 2013

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" ],