chrome.storage.sync.get始终返回默认值

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

我正在开发chrome扩展程序,它要求我跟踪扩展程序的最后运行日期。为此,我使用chrome.storage.sync,但是,get调用始终返回我设置为默认值的值。下面是代码。

 chrome.storage.sync.get({theDate: {}}, function (dateResult) {
    let currentDate = new Date();
    let setDate = dateResult.theDate; // always set to {}
    if (Object.keys(setDate).length === 0){ //if date has never been set before
        setDate = currentDate;
    }
    if (setDate.toLocaleDateString() !== currentDate.toLocaleDateString()){
          //do stuff if it is a different day than the last time extension was run
    }


    chrome.storage.sync.set({theDate: currentDate}, function () {
        console.log("Current date set.");

    });

});
google-chrome-extension chrome-extension-async
2个回答
2
投票

Chrome扩展存储API仅支持与JSON兼容的类型,例如字符串,数字,布尔值以及由这些基本类型组成的数组/对象。

Date对象不是JSON',因此无法存储。 你可以存储Date.now()这是一个数字。

chrome.storage.sync.get({theDate: Date.now()}, ({theDate}) => {
  if (new Date(theDate).toLocaleDateString() !== new Date().toLocaleDateString()) {
    // do stuff if it is a different day than the last time extension was run
  }
  chrome.storage.sync.set({theDate: Date.now()});
});

1
投票

您需要在存储之前对Date对象进行字符串化。使用JSON.stringifyString构造函数。或者,您可以将Date称为普通函数而不是构造函数来获取字符串对象而不是Unix时间戳;或者,更好的是,正如wOxxOm建议的那样,使用Date.now()将日期作为一个数字,以毫秒为单位。 1

我还必须注意,在第一个条件中,你检查从存储中检索的Date对象是否有任何键,但它不应该,即使你可以存储原始的Date对象。您可能误解了存储中数据的设置方式。基本上dateResult === {theDate: currentDate}dateResult.theDate === currentDate2

编辑:包括wOxxOm的完整性建议。

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