gpt4 book ai didi

javascript - 检查数据是否已存在于 chrome.storage.sync 中

转载 作者:行者123 更新时间:2023-11-30 16:57:46 24 4
gpt4 key购买 nike

我有一个函数可以从 chrome.storage 获取数据并将其加载到一个数组中,如果我使用一行代码将一个空数组保存到 chrome.storage 中,然后在以用户身份使用扩展程序之前将其取出,则一切正常会的。

问题是用户不能这样做,如果我第一次启动扩展而不这样做,那么它看起来像 chrome 将未定义的传递回导致此错误的变量:

"Uncaught TypeError: Cannot read property '8' of undefined"

在这一行:

if (SavedReminders[i][8] == "Full") {

我不完全确定到底发生了什么,但我想如果有一种方法可以检查数据是否已经存在于 chrome.storage 中,或者有一种方法可以在用户第一次打开时保存一个空数组可以修复它的扩展。

这是我的加载函数:

function LoadFromFile() {
reminds = {}
chrome.storage.sync.get({ reminds: [] }, function (result) { SavedReminders = result.reminds });
}

和保存功能:

function SaveToFile() {
reminds={}
chrome.storage.sync.set({reminds:SavedReminders },
function () {
console.log(SavedReminders, reminds);
});
}

如有任何帮助,我们将不胜感激。

最佳答案

您可以将一个对象(而不是一组键)传递给 api,每个键都有默认值。它将返回不存在的键的默认值。
你也可以保持原样并检查它是否 ==undefined 但我建议的方法更清晰。
有关如何传递此类对象的详细信息,请参阅 .storage 的官方 api 文档:

https://developer.chrome.com/extensions/storage存储区方法:获取StorageArea.get(字符串或字符串数​​组或对象键,函数回调)(可选)键:...“或指定默认值的字典”...

所以chrome.storage.local.get({foo:"hi", bar:"there"})将在尚未保存时返回 obj,其中 obj["foo"] 为“hi”。

关于javascript - 检查数据是否已存在于 chrome.storage.sync 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com