Chrome.storage set \ get clarification

I want to save information in my extenstion. I use Chrome.storage.sync for this, however, when I read immediately after saving, I cannot get the value correctly. I’m probably doing something stupid .... I tried to clear the local storage chrome.storage.sync.clear , but that didn’t help.

My save function (seeing how Currently did this):

 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 like:

 Storage.save("", 'path',username); console.log(Storage.load("",'path')); 

The result is the following:

saved data

undefined

read: [object Object]


Update:

OK, apparently, there is a problem in how to pass a key-value pair to an object, because when I call it like this: chrome.storage.sync.set({'path':username}, function(){});

Printing storage in the console produces a better result:

undefined

Shay

Not sure what this undefined is ...


Update 2:

After successfully writing to the repository, trying to read it when the document is ready. Using the following code:

 var dbdata = chrome.storage.sync.get("path",function(object){ return object['path']; }); 

However, the body of the function is not executed, although the documentation says that it will be launched in any case and will set lastError in case of an error.

Any suggestions?

+6
source share
1 answer

The return value from the function you pass to chrome.storage.sync does not do what you expect. The value is available only in the callback. It does not end with dbdata .

Moreover:

chrome.storage.sync is an asynchronous API.

You need to wait until it finishes before you can get the data.

 chrome.storage.sync.set({'value': 12}, function() { chrome.storage.sync.get("value", function(data) { console.log("data", data); }); }); 

and output:

 data Object {value: 12} 

manifest.json should contain:

"Permissions": ["storage location"],

+14
source

All Articles