Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

javascript - 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'}
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...