gpt4 book ai didi

google-chrome-extension - chrome.storage 可以保存 "advanced"对象,比如日期或 map 吗?

转载 作者:行者123 更新时间:2023-12-05 01:10:40 25 4
gpt4 key购买 nike

我制作了一个 chrome 扩展来管理互联网历史记录、浏览器 cookie 等。如果你一周没有运行它,我会尝试发出通知,所以我使用了 chrome.storage在您使用扩展程序时保存时间戳。


这是我的代码:

function clear()
{
chrome.browsingData.removeHistory({"since":0}, callback);
var now = new Date();
chrome.storage.local.set({key: now}, function() {
console.log('Value is set to ' + now)
}

(回调是一个空函数)


<背景.js>

chrome.storage.local.get(["key"], function(result) {
alert (result.key)
});

当我测试它时,它给了我:

[object Object]

为什么这段代码给我的是这个,而不是我保存的时间戳?

最佳答案

JSON 类型

chrome.storage,就像扩展 messaging在 Chrome 中,仅支持与 JSON 兼容的类型:

  • 数字但不是 BigInt
  • 字符串
  • boolean truefalse
  • null 但不是 undefined
  • 由上述简单类型组成的对象/数组
    • 可以嵌套
    • 不能有循环自引用
    • 键必须是字符串而不是 Symbol
    • 不支持的部分将被剥离,因此复杂类型将生成 {}

不支持DOM元素、类实例、Set、Map、RegExp、Date等。
这些将存储为 {}

要查看实际存储的内容,请在您的代码或 devtools 控制台中运行:

console.log(JSON.parse(JSON.stringify(obj)))

日期的解决方案

存储 Date.now() 这是一个数字:

chrome.storage.local.set({foo: Date.now()})

重新创建日期:

chrome.storage.local.get('foo', data => {
const date = new Date(data.foo);
// use it here
})

Set/Map的解决方案

存储:

chrome.storage.local.set({foo: [...map]})

阅读:

chrome.storage.local.get('foo', data => {
const map = new Map(data.foo);
// use it here
})

媒体对象的替代方案

  • 转换为数据 URI 字符串。
  • 转换为 ArrayBuffer 并存储在 IndexedDB 中。

附:不要使用 + 来连接 console.log 中的字符串和对象。像这样使用 ,:console.log('Value is set to', now)

关于google-chrome-extension - chrome.storage 可以保存 "advanced"对象,比如日期或 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63911640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com