关闭和打开 chrome 扩展弹出窗口时如何不丢失数据
我是 chrome 扩展的新手.我需要在使用弹出窗口时创建数据,在关闭并重新打开它后可用.
I'm new to chrome extension. I need to have data created when working with the popup, available after closing and re-opening it.
以下是有关我的具体问题的更多详细信息:
Here're some more details about my specific problem:
每当我的 chrome 扩展弹出窗口打开时,脚本就会运行.在弹出窗口中有一个选项可以单击按钮,该按钮会将项目添加到数组中,用于在此弹出窗口的另一个选项卡中显示此项目列表.但是,由于每次打开弹出窗口时代码都会重新运行,因此数组在弹出窗口再次打开的那一刻被清空,显然是在浏览器或操作系统重新启动时.我需要这个数组通过打开和关闭操作系统、浏览器和弹出窗口本身来保持一致.有什么想法吗?
whenever my chrome extension popup is opened a script runs. in the popup there's an option to click a button which will add an item to an array, which is used in order to display this list of items in another tab in this popup. However, since every time the popup is opened the code runs all over again, the array is emptied the moment the popup opens again, and obviously when the browser or the OS is restarted. I need this array to stay consistent through opening and closing of the OS, the browser and the popup itself. Any ideas?
顺便说一句 - 从后台页面管理它还不够好,因为重新启动操作系统的那一刻后台页面会话停止并且数据丢失
btw - managing it from a background page is not good enough since the moment the os is restarted the background page session stops and the data is lost
推荐答案
当一个弹窗关闭时,它的 HTML 文档被完全卸载;您需要在每次打开弹出窗口时恢复状态.没办法.
When a popup is closed, its HTML document is completely unloaded; you need to restore state when your popup loads every time it's opened. No way around that.
正如您所提到的,可以在浏览器运行时在后台页面中保留状态信息.但它仍然是临时存储;您需要使用持久存储来保存您需要保存的任何状态.
As you mention, it's possible to persist state information in the background page while the browser is running. But it's still temporary storage; you need to use persistent storage to save whatever state you need to save.
最明显(也是推荐)的选择是 chrome.storage
API,专为此目的而设计.如果您愿意,还可以使用 Web API,例如 localStorage
或 IndexedDB
.
The most obvious (and recommended) choice is chrome.storage
API, specifically designed for this purpose. You can also use Web APIs such as localStorage
or IndexedDB
if you like.
相关文章