首页 > 解决方案 > 使用 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

标签: javascriptgoogle-chrome-extension

解决方案


代码有三个错误:

  • 不正确地使用变量来生成对象文字,
    而不是{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);
  });
});

推荐阅读