javascript - 使用 chrome.storage.sync.set() 为 Chrome 扩展存储动态列表
问题描述
我正在尝试存储一个对象,将一个字符串映射到一个列表,使用chrome.sync.get
. 我的目标是为不存在的键创建一个新列表,或者如果键存在,则将一个元素附加到列表中。但是,我无法填充该对象。当我尝试检索之前插入的值时,我得到一个空对象作为返回值。以下是我正在使用的代码:
let currentTabId = '234';
let spawnedTabId = '390';
chrome.storage.sync.get(currentTabId, function(data) {
if (typeof data.currentTabId === 'undefined') {
chrome.storage.sync.set({currentTabId: [spawnedTabId]}, function() {
console.log("Initialized "+currentTabId+" with "+spawnedTabId);
});
chrome.storage.sync.get(currentTabId, function(data) {
console.log(data);
});
} else {
data.currentTabId.push(spawnedTabId)
chrome.storage.sync.set({currentTabId: data.currentTabId}, function() {
console.log("Appended "+spawnedTabId+" to "+currentTabId);
});
}
});
我得到的输出是:
>>> Initialized 234 with 390
>>> {}
__proto__: Object
解决方案
代码有三个错误:
- 不正确地使用变量来生成对象文字,
而不是{variable: value}
它应该是{[variable]: value}
,更多信息 - 不正确地使用变量从对象中读取属性,
而不是obj.variable
应该obj[variable]
- 异步 API 使用不当,
数据应在写入后读取,即在回调中读取。
let key = '234';
let spawnedTabId = '390';
chrome.storage.sync.get(key, data => {
const spawned = data[key] || [];
spawned.push(spawnedTabId);
chrome.storage.sync.set({ [key]: spawned }, () => {
// now you can read the storage:
// chrome.storage.sync.get(key, console.log);
});
});
推荐阅读
- javascript - 从 Chrome 获取包含更改的 PDF
- javascript - 将对象数组变成有组织的对象 - javascript
- python - Python在离散数据上查找局部最大值和最小值
- python - 如何让这段代码更快地找到大数的自然除数?
- c++ - (no match for operator[])//C++ 在我尝试在我的函数上使用数组时向我显示该错误
- authentication - 用于 R 身份验证的 Rtweet 包:错误 401
- python - 如何将 .csv 文件中的特定列加载到二维数组中?Python
- ios - React Native iOS - CocoaPods 找不到 Flipper-Folly 的兼容版本,它们需要更高的最小部署目标
- python - 是否可以从 python websocket 读取并写入 kafka 主题?
- javascript - 用 Jest 模拟 NextJS 路由器事件