How to use chrome.storage in a chrome extension using a variable's value as the key name?

后端 未结 2 1693
忘掉有多难
忘掉有多难 2020-12-30 02:31

I\'m trying to use chrome\'s local storage / sync storage (chrome.storage) for an extension, to store data entries, for many different entries. I can\'t seem to figure out

相关标签:
2条回答
  • 2020-12-30 03:13

    Use a named object, not an anonymous object, and set a member variable using square brackets:

    var dataObj = {};
    dataObj[imageName] = myDescription;
    chrome.storage.local.set(dataObj, function() { /*...*/ });
    

    It's not the most elegant looking code, but it's the only way to do it.

    In ES6, a slightly shorter approach is to use an object literal with a dynamic property name:

    chrome.storage.local.set({
        [imageName]: myDescription
    }, function() { /*...*/ });
    
    0 讨论(0)
  • 2020-12-30 03:20

    the set method accepts object items, and an optional callback, the get accepts optional string or array or object keys and if you passed the first argument, you got to pass the second argument as well.

    Example:

    // To set 
    chrome.storage.local.set({'testKey':'Test Value'});
    
    // To get
    chrome.storage.local.get('testKey', function(data){
      console.log(data); 
      // logs out "Object {testKey: "Test Value"}"
    })
    
    0 讨论(0)
提交回复
热议问题