How to store Set object in chrome local storage

不问归期 提交于 2021-01-20 04:58:07

问题


var testSet = new Set(); testSet.add(1); testSet.add(2);
chrome.storage.local.set( { 'key': testSet }, function() { chrome.storage.local.get( 'key', function(data){ console.log(data) }); });

This outputs

Object {key: Object}
key: Object__proto__: 
Object__proto__: Object

Why doesn't it show the testSet values in there?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37850661/how-to-store-set-object-in-chrome-local-storage

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