Using a variable key in chrome.storage.local.set [duplicate]

天大地大妈咪最大 提交于 2019-11-29 08:02:32

In JavaScript, the only way to use a non-static variable name is by assigning a value as a property, instead of using object literals.

var key = 'myKey';
var param1 = 'whatever';
chrome.storage.local.get(key, function(val) {
    // Create property if does not exist (yet)
    if (typeof val[key] != 'string') val[key] = '';
    // Append value of param1
    val[key] += param1;
    // Save data
    chrome.storage.local.set(val);
    alert(val[key]);
});

Note: You might want to verify that set succeeded. This can be done by using a callback. For instance:

    chrome.storage.local.set(val, function() {
        if (chrome.extension.lastError) {
            alert('An error occurred: ' + chrome.extension.lastError.message);
        }
    });
Syam Kumar S

I have solved the problem. Instead of using chrome.storage.local.set({key:val[key]+param1});

I have replaced the json string {key:val[key]+param1} with an object.

var obj = {};       
var key = "myKey";  
obj[key] += param1;   
chrome.storage.local.set(obj);

Here obj has value {"myKey":"the appended value"}

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