Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.storage.sync.set not saving values

So I've run into a bit of snag with regards to local storage on Google Chrome. From what I've researched, my syntax seems to be correct, but for some reason the value is not being saved. Here's my code:

chrome.storage.sync.get(accName, function(data) {
    var accData = data[accName];
    // Stuff
    chrome.storage.sync.set({ accName: accData }, function() {
        alert('Data saved');
    });
});

Every time I re-run it, data[accName] returns undefined. I've tried the same code with literal values for the sync.set parameters (eg. { 'john32': ['fk35kd'] }), and that seems to work, so I'm really confused as to what the issue could be. Any help would be appreciated.

like image 366
Drazen Bjelovuk Avatar asked Jun 26 '13 23:06

Drazen Bjelovuk


People also ask

How does storage sync work in chrome?

When using storage.sync, the stored data will automatically be synced to any Chrome browser that the user is logged into, provided the user has sync enabled. When Chrome is offline, Chrome stores the data locally. The next time the browser is online, Chrome syncs the data.

How do I get the current value in chrome storage?

chrome. storage. local. get (['key'], function (result) {console. log ('Value currently is ' + result. key);}); When using storage.sync, the stored data will automatically be synced to any Chrome browser that the user is logged into, provided the user has sync enabled. When Chrome is offline, Chrome stores the data locally.

What happens to my data when I Turn Off Chrome Sync?

When Chrome is offline, Chrome stores the data locally. The next time the browser is online, Chrome syncs the data. Even if a user disables syncing, storage.sync will still work. In this case, it will behave identically to storage.local. Confidential user information should not be stored!

How do I save a variable in chrome?

So we use the following method to save. chrome.storage.sync.set ( {'variable_name': 'variable_value'}, function () { console.log ("you saved me!!"); });


1 Answers

The issue was trying to plug accName into an object literal inside the set statement (credit to Rob above). What I'd end up with was an object with a property 'accName' rather than the value of accName itself. Here's a fix.

var obj = {};
obj[accName] = accData;
chrome.storage.sync.set(obj, function() {
    alert('Data saved');
});

Update

ES6 now allows computed property names in object literals, so the above can be achieved with:

chrome.storage.sync.set({ [accName]: accData }, function() {
    alert('Data saved');
});
like image 187
Drazen Bjelovuk Avatar answered Sep 20 '22 23:09

Drazen Bjelovuk