chrome.storage 可以保存日期或地图等“高级”对象吗?

问题描述 投票:0回答:1

我制作了一个 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)
}

(回调是一个空函数)


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

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

[object Object]

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

google-chrome-extension local-storage
1个回答
10
投票

JSON 类型

在 Chrome/chromium 中,

chrome.storage
,就像扩展消息传递一样,仅支持 JSON 兼容类型:

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

不支持 DOM 元素、函数、Set、Map、RegExp、Date 等。
这些将存储为

{}

它不支持 toJSON() 自定义方法,因此如果您想使用这些方法,则必须存储

JSON.stringify(obj)
并在读取时调用
JSON.parse(str)

日期解决方案

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

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

要重新创建日期:

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

套装/地图解决方案

储存:

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)

© www.soinside.com 2019 - 2024. All rights reserved.