Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...