Kat*_*tie 4 google-chrome-extension google-chrome-storage
在 Chrome 扩展程序中,我试图将 Date 对象保存到存储中,然后将其读回。根据官方文档,
具有“对象”和“函数”类型的值通常会序列化为 {},但 Array(按预期序列化)、Date 和 Regex(使用其字符串表示形式序列化)除外。
我保存到存储为:
var value= new Date(Date.now());
chrome.storage.sync.set({"testdate":value}, function(){
console.log("saved testdate to storage:");
console.log(value);
});
Run Code Online (Sandbox Code Playgroud)
记录值的输出是
2018 年 10 月 16 日星期二 08:22:11 GMT-0700(太平洋夏令时)
我后来从存储中检索为:
chrome.storage.sync.get("testdate", function(items){
console.log("test date from storage:");
console.log(items.testdate);
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,logging items.testdate 的值是:
对象 原型:构造函数:ƒ对象()hasOwnProperty:ƒhasOwnProperty()isPrototypeOf:ƒisPrototypeOf()propertyIsEnumerable:ƒpropertyIsEnumerable()的toLocaleString:ƒ的toLocaleString()的toString:ƒ的toString()的valueOf:ƒ的valueOf() defineGetter:ƒ defineGetter( ) defineSetter:ƒ defineSetter() lookupGetter:ƒ lookupGetter() lookupSetter:ƒ lookupSetter()获得原:ƒ原()组原:ƒ原()
无法弄清楚如何取回我的日期对象(或转换回日期的字符串表示)
小智 5
const currentTime = (new Date()).toJSON();
const items = { 'testdate': currentTime };
chrome.storage.local.set(items, () => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
Run Code Online (Sandbox Code Playgroud)
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);
}
});
Run Code Online (Sandbox Code Playgroud)
我的代码基于Date.prototype.toJSON,它说
Run Code Online (Sandbox Code Playgroud)var jsonDate = (new Date()).toJSON(); var backToDate = new Date(jsonDate); console.log(jsonDate); //2015-10-26T07:46:36.611Z
从 Chrome storage official documentation,我认为它说 Date 不会按预期序列化。因为它指定了 Array 和 Regex 如何序列化为,但没有指定 Date 如何序列化,我认为它序列化为{}
,这是我没有包含toJSON()
零件时得到的。
一个对象,它为每个键/值对更新存储。存储中的任何其他键/值对都不会受到影响。数字等原始值将按预期序列化。具有“对象”和“函数”类型的值通常会序列化为 {},但 Array(按预期序列化)、Date 和 Regex(使用其字符串表示形式序列化)除外。
归档时间: |
|
查看次数: |
575 次 |
最近记录: |