我在尝试使用 chrome.storage.local.set 保存集时遇到了困难。
我已经测试过将集合包含在对象文字中,希望它能够保存,因为对象似乎是可保存的,但它不起作用。不知何故,它实际上可以在 Firefox 上运行,但在 chrome 上失败。
let test = new Set(["a","b","c"]);
console.log(test);
chrome.storage.local.set({testing: test}, function() {
chrome.storage.local.get(["testing"], function(item) {
console.log(item);
});
});
console.log(item) 打印出与测试相关的键值,但其中没有任何内容,该集合未保存。
最佳答案
那是因为数据是序列化的以便存储
Primitive values such as numbers will serialize as expected. Values with a typeof "object" and "function" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation).
要解决此问题,您可以在存储时将 Set
转换为数组,然后在检索时将其转换回 Set
。
这是一个例子:
let test = new Set(["a","b","c"]);
console.log(test);
chrome.storage.local.set({testing: [...test]}, function() {
chrome.storage.local.get(["testing"], function(item) {
if (item.testing) {
const retrievedTest = new Set(item.testing);
}
});
});
关于javascript - 无法使用 chrome.storage.local.set 保存集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215709/