user1558225 user1558225 - 1 month ago 5
Javascript Question

chrome.storage.local.set using a variable key name

In a Google Chrome Extension, I want to use

(as opposed to localStorage) because:


  1. With key-value pairs, the value can be any object (as opposed to string only)

  2. Changes to the data model using setter
    storage.set
    can trigger an event listener



Using
storage.set
, how can I have a variable key name?

Note: If I don't use the setter, I can do
storage[myTestVar]
, but changes to the object won't trigger the event listener.

var storage = chrome.storage.local;
var myTestVar = 'myVariableKeyName';

storage.set({myTestVar:'my test var'});

storage.get(myTestVar,function(result){
console.log(myTestVar,result);
//console output = myVariableKeyName {}
});
storage.get('myTestVar',function(result){
console.log(result);
//console output = {myTestVar:'my test var'}
});

Answer

Is this what you where looking for?

var storage = chrome.storage.local;

var myTestVar = 'myVariableKeyName';

var obj= {};

obj[myTestVar] = 'my test var';

storage.set(obj);

storage.get(myTestVar,function(result){
  console.log(myTestVar,result);
  //console output = myVariableKeyName {myTestVar:'my test var'}
});

storage.get('myTestVar',function(result){
  console.log(result);
  //console output = {myTestVar:'my test var'}
})
Comments