Javascript Chrome扩展弹出窗口未使用Chrome.storage.sync持久化数据集
我正在尝试构建一个Chrome扩展,它主要由一个弹出应用程序组成。问题是,每当我点击弹出窗口(关闭它),我设置的数据就会消失。使用存储资源管理器扩展以及我自己的调试控制台日志,我可以确保它被设置为chrome.Storage.sync,但每次我重新打开它时,所有数据都消失了 我是否从根本上误解了API的用途?我使用的是React and building to a popup.html,我没有content.js或background.js。我是否需要发送消息以使数据持久化 下面是我的React App.jsx中的相关代码。我有一个sync函数,用于同步Javascript Chrome扩展弹出窗口未使用Chrome.storage.sync持久化数据集,javascript,google-chrome,google-chrome-extension,google-chrome-app,Javascript,Google Chrome,Google Chrome Extension,Google Chrome App,我正在尝试构建一个Chrome扩展,它主要由一个弹出应用程序组成。问题是,每当我点击弹出窗口(关闭它),我设置的数据就会消失。使用存储资源管理器扩展以及我自己的调试控制台日志,我可以确保它被设置为chrome.Storage.sync,但每次我重新打开它时,所有数据都消失了 我是否从根本上误解了API的用途?我使用的是React and building to a popup.html,我没有content.js或background.js。我是否需要发送消息以使数据持久化 下面是我的React
所有数据(这只是一个对象数组)和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"
}
}
将传递一个对象,该对象的数据作为键值属性,而不是直接传递给您的数据。因此,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: [] });
});
}
包括实际使用chrome.storage.sync
@PatrickEvans有效点的扩展代码,添加了一些简短的示例。哦,天哪,它可以工作。你可能会认为,通过将属性的名称作为第一个参数传递,它只会返回单个属性,而不是所有属性的对象,有点不直观,这就是为什么我想我没有想到这一点。非常感谢你!