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

吃可爱长大的小学妹 提交于 2019-12-28 01:55:47

问题


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'}
});

回答1:


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'}
})



回答2:


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);
});


来源:https://stackoverflow.com/questions/11692699/chrome-storage-local-set-using-a-variable-key-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!