简体   繁体   中英

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

In a Google Chrome Extension, I want to use chrome.storage.local (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[v1] , but changes to the object won't trigger the event listener.

var storage = chrome.storage.local;
var v1 = 'k1';

storage.set({v1:'s1'});

storage.get(v1,function(result){
    console.log(v1,result);
    //console output = k1 {}
});
storage.get('v1',function(result){
    console.log(result);
    //console output = {v1:'s1'}
});

Is this what you where looking for?

var storage = chrome.storage.local;

var v1 = 'k1';

var obj= {};

obj[v1] = 's1';

storage.set(obj);

storage.get(v1,function(result){
  console.log(v1,result);
  //console output = k1 {v1:'s1'}
});

storage.get('v1',function(result){
  console.log(result);
  //console output = {v1:'s1'}
})

It's 2016, and Chrome (and Firefox, and Edge - everyone using Chrome extension model) support ES6 Computed Property Names .

With that, the task becomes simpler:

var storage = chrome.storage.local;
var v1 = 'k1';

storage.set({
  [v1]: 's1' // Will evaluate v1 as property name
});

storage.get(v1, function(result) {
    console.log(v1, result);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM