Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 834
Syam Kumar S Avatar asked Jan 14 '23 03:01

Syam Kumar S


1 Answers

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);
        }
    });
like image 194
Rob W Avatar answered Jan 16 '23 21:01

Rob W