【发布时间】:2019-02-10 02:21:37
【问题描述】:
我正在尝试构建一个主要由弹出应用程序组成的 Chrome 扩展程序。问题是,每当我点击弹出窗口(关闭它)时,我设置的数据就会消失。使用存储资源管理器扩展以及我自己的调试控制台日志,我可以确定它已设置为 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"
}
}
【问题讨论】:
-
包含实际使用
chrome.storage.sync的扩展代码 -
@PatrickEvans 有效点,添加了一些简短的例子。
标签: javascript google-chrome google-chrome-extension google-chrome-app