chrome.storage.sync.set不保存值 [英] chrome.storage.sync.set not saving values

查看:691
本文介绍了chrome.storage.sync.set不保存值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在Google Chrome浏览器本地存储方面遇到了一些麻烦。从我研究的内容来看,我的语法似乎是正确的,但由于某些原因,价值并未得到保存。这里是我的代码:

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');
    });
});

每当我重新运行它时, data [accName] 返回undefined。我已经尝试了sync.set参数的字面值相同的代码(例如 {'john32':['fk35kd']} ),这似乎工作,所以我很困惑这个问题是什么。任何帮助将不胜感激。

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.

推荐答案

感谢罗布。如上所述,问题是试图将 accName 插入set语句内的对象字面值。我最终得到的是一个带有属性'accName'的对象,而不是 accName 本身的值。这是一个修复。

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');
});



更新



ES6现在允许计算对象文字中的属性名称,所以以上可以通过以下方式实现:

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');
});

这篇关于chrome.storage.sync.set不保存值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆