chrome.storage.sync.set not saving values

久未见 提交于 2020-01-01 05:39:26

问题


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.


回答1:


Thanks Rob. As stated, the issue was trying to plug accName into an object literal inside the set statement. 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');
});


来源:https://stackoverflow.com/questions/17331957/chrome-storage-sync-set-not-saving-values

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