Syam Kumar S Syam Kumar S - 1 month ago 6
Javascript Question

Using a variable key in chrome.storage.local.set

I am creating a chrome-extension.
I don't know how to use a variable as the key to

chrome.storage.local.set()
function. I have tried

var key = 'myKey';
chrome.storage.local.get(key, function(val) {
chrome.storage.local.set({key:val[key]+param1}); //appending param1
alert(val[key]);
}


Here i am trying to get the value of
val[key]
and append a string
param1
and place it back to the storage using the same key. But I am not able to do so.
the alert box displays undefined all the time.




But when I try without the variable
key
, it works fine.

chrome.storage.local.get('myKey', function(val) {
chrome.storage.local.set({myKey:val['myKey']+param1}); //appending param1
alert(val['myKey']);
}


The problem is that I am using
chrome.storage.local.set
can have arguments of not only string but also objects.

Answer

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"}