我制作了一个 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]
为什么这段代码给了我这个,而不是我保存的时间戳?
在 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
})
附注不要使用
+
连接 console.log 中的字符串和对象。像这样使用 ,
:console.log('Value is set to', now)