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(ke
Solution 1:
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 param1val[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);
}
});
Post a Comment for "Using A Variable Key In Chrome.storage.local.set"