Chrome扩展程序弹出窗口未使用chrome.storage.sync保留数据集

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

我正在尝试构建一个主要由弹出式应用组成的Chrome扩展程序。问题是每当我点击弹出窗口(关闭它)时,我设置的数据就会消失。使用Storage Explorer扩展以及我自己的调试控制台日志,我可以确定它已设置为chrome.storage.sync,但每次重新打开它时,所有数据都消失了。

我是否从根本上误解了如何使用API​​?我正在使用React并构建到popup.html,我没有content.js或background.js。我是否需要发送消息才能保留数据?

这是我的React App.jsx中的相关代码。我有一个同步功能,我用它来同步allData(它只是一个对象数组)和componentWillMount中的数据获取器:

const syncChanges = (allData) => {
  chrome.storage.sync.set({ allData }, () => {
    chrome.storage.sync.get('allData', data => console.log(data));
  });
};

componentWillMount() {
  // On app load, check if there's existing data. If not, set it.
  chrome.storage.sync.get('allData', (allData) => {
    console.log(allData);
    if (allData.length) {
      this.setState({ allData });
    } else chrome.storage.sync.set({ allData: [] });
  });
}

其他值得注意的是,在扩展的细节中它没有显示存储权限,即使我在manifest.json中设置它,并且它没有给我使用API​​的错误。下面是我的manifest.json,但对我来说似乎很好。

{
  "name": "Leetcode Reminders",
  "description": "A Chrome extension to remind users about Leetcode problems they should revisit.",
  "manifest_version": 4,
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Leetcode Reminders"
  },
  "version": "1.0",
  "permissions": [
    "storage",
    "declarativeContent",
    "tabs"
  ],
  "icons": {
    "64": "favicon.png"
  }
}
javascript google-chrome google-chrome-extension google-chrome-app
1个回答
2
投票

chrome.storage.sync.get callback传递一个对象,数据作为键值属性,而不是直接传递给您的数据。因此,您的allData变量不是您保存的数组,而是包含它的对象。因此它没有length属性(除非您保存了名为length的数据)。

因此,在每个开口处,您将数据重置为空数组,因为if(allData.length)将测试为false,因为length不存在。

检查相应的属性名称(在您的情况下为.allData),以查看是否已设置数据

componentWillMount() {
  // On app load, check if there's existing data. If not, set it.
  chrome.storage.sync.get('allData', (result) => {
    console.log(result.allData);
    //use "in" check as a regular if(result.allData) will
    //return false for empty arrays
    if ( 'allData' in result ) {
      this.setState({ allData });
    } else chrome.storage.sync.set({ allData: [] });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.