How to store Set object in chrome local storage

前端 未结 2 1218
小蘑菇
小蘑菇 2021-01-19 06:12
var testSet = new Set(); testSet.add(1); testSet.add(2);
chrome.storage.local.set( { \'key\': testSet }, function() { chrome.storage.local.get( \'key\', function(dat         


        
相关标签:
2条回答
  • 2021-01-19 06:25

    From the chrome API docs:

    StorageArea.get(string or array of string or object keys, function callback)
    

    So it looks like you can only use primitives and objects containing primitives.

    0 讨论(0)
  • 2021-01-19 06:44

    One way to achieve this, is by converting your Set into an array by using Spread Operator.

    E.g.

    var testSet = new Set(); testSet.add(1); testSet.add(2);
    chrome.storage.local.set({ 'key': [...testSet] });
    

    And when you want to retrieve it, you can do it like..

    chrome.storage.local.get('key', function(data){ 
        var mySet = new Set(data.key);
        console.log(mySet);
    })
    

    Edit: Thanks for Xan's comment to notice that chrome.storage could set an array directly.

    0 讨论(0)
提交回复
热议问题