chrome.storage 可以保存 "advanced" 日期或地图等对象吗?
Can chrome.storage save "advanced" objects like Date or Map?
我制作了一个 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]
为什么这段代码给我的是这个,而不是我保存的时间戳?
JSON 类型
chrome.storage,就像Chrome中的扩展messaging一样,只支持JSON-compatible类型:
- 数字但不是
BigInt
- 字符串
- 布尔值
true
和 false
null
但不是 undefined
- objects/arrays由以上简单类型组成
- 可以嵌套
- 不能有循环self-references
- 键必须是字符串而不是
Symbol
- 不受支持的部分将被剥离,因此复杂类型将生成
{}
它不支持 DOM 个元素、class 个实例、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.
P.S。不要使用 +
连接 console.log 中的字符串和对象。像这样使用 ,
:console.log('Value is set to', now)
我制作了一个 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]
为什么这段代码给我的是这个,而不是我保存的时间戳?
JSON 类型
chrome.storage,就像Chrome中的扩展messaging一样,只支持JSON-compatible类型:
- 数字但不是
BigInt
- 字符串
- 布尔值
true
和false
null
但不是undefined
- objects/arrays由以上简单类型组成
- 可以嵌套
- 不能有循环self-references
- 键必须是字符串而不是
Symbol
- 不受支持的部分将被剥离,因此复杂类型将生成
{}
它不支持 DOM 个元素、class 个实例、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.
P.S。不要使用 +
连接 console.log 中的字符串和对象。像这样使用 ,
:console.log('Value is set to', now)