在 Chrome 扩展中,我试图将 Date 对象保存到存储中,然后将其读回。根据official documentation ,
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).
我保存到存储为:
var value= new Date(Date.now());
chrome.storage.sync.set({"testdate":value}, function(){
console.log("saved testdate to storage:");
console.log(value);
});
记录值的输出是
Tue Oct 16 2018 08:22:11 GMT-0700 (Pacific Daylight Time)
我后来从存储中检索为:
chrome.storage.sync.get("testdate", function(items){
console.log("test date from storage:");
console.log(items.testdate);
});
在这种情况下,记录 items.testdate 的值为:
Object proto: constructor: ƒ Object() hasOwnProperty: ƒ hasOwnProperty() isPrototypeOf: ƒ isPrototypeOf() propertyIsEnumerable: ƒ propertyIsEnumerable() toLocaleString: ƒ toLocaleString() toString: ƒ toString() valueOf: ƒ valueOf() defineGetter: ƒ defineGetter() defineSetter: ƒ defineSetter() lookupGetter: ƒ lookupGetter() lookupSetter: ƒ lookupSetter() get proto: ƒ proto() set proto: ƒ proto()
无法弄清楚如何取回我的 Date 对象(或将字符串表示形式转换回 Date)
最佳答案
设置面
const currentTime = (new Date()).toJSON();
const items = { 'testdate': currentTime };
chrome.storage.local.set(items, () => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
得到边
chrome.storage.local.get(['testdate'], (result) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
} else {
const storedJSONDate = result['testdate'];
const testdate = new Date(storedJSONDate);
console.log(testdate);
}
});
来源
我的代码基于 Date.prototype.toJSON它说
var jsonDate = (new Date()).toJSON(); var backToDate = new Date(jsonDate); console.log(jsonDate); //2015-10-26T07:46:36.611Z
来自 Chrome 存储 official documentation ,我认为这是说 Date 不会按预期进行序列化。因为它指定了 Array 和 Regex 如何序列化,而不是 Date 如何序列化,所以我认为它序列化为
{}
,这是我没有包含 toJSON()
时得到的部分。An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. 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).
关于javascript - 从 chrome 存储中检索日期对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52838988/