最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - chrome.storage.sync.set not saving values - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Mar 12, 2018 at 20:37 Drazen Bjelovuk asked Jun 26, 2013 at 23:09 Drazen BjelovukDrazen Bjelovuk 5,4725 gold badges43 silver badges67 bronze badges 1
  • 3 possible duplicate of Using a variable key in chrome.storage.local.set (the problem is caused by a wrong method to set the value, your getter is OK.) – Rob W Commented Jun 27, 2013 at 8:04
Add a comment  | 

1 Answer 1

Reset to default 19

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');
});
发布评论

评论列表(0)

  1. 暂无评论