[前端]CRX持久化
在 Chrome 扩展开发中,持久化保存数据通常使用 Chrome 的 storage
API。storage
API 提供了两种存储选项:local
和 sync
。使用 local
存储的数据保存在本地浏览器中,只能在同一设备上访问。使用 sync
存储的数据可以在用户登录其 Google 帐户的所有设备上同步。由于你提到使用的是 crxjs
,这可能是通过 Vite 生态系统来构建 Chrome 扩展。以下是如何使用 storage
API 来持久化保存数据的基本方法:
使用 chrome.storage.local
1. 存储数据
将数据存储在本地:
chrome.storage.local.set({ key: 'value' }, function() {
console.log('Data is stored locally');
});
2. 获取数据
从存储中获取数据:
chrome.storage.local.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
3. 监听存储变化
如果需要监听数据变化:
chrome.storage.onChanged.addListener(function(changes, area) {
if (area === 'local') {
console.log('Storage area "local" has changed');
console.log(changes);
}
});
使用 chrome.storage.sync
1. 存储数据
将数据存储在同步存储中,可以在不同设备之间同步:
chrome.storage.sync.set({ key: 'value' }, function() {
console.log('Data is stored and will sync across devices');
});
2. 获取数据
从同步存储中获取数据:
chrome.storage.sync.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
注意事项
- 权限:确保在
manifest.json
中请求所需的权限。
{
"manifest_version": 3,
"name": "Example Extension",
"version": "1.0",
"permissions": [
"storage"
],
"action": {/* your other configurations */}
}
-
数据限制:
chrome.storage.sync
有较小的存储限额(推荐用来存储较小的重要配置),而chrome.storage.local
的存储限额则较大。 -
异步操作:
storage
API 的方法是异步的,因此使用回调函数来处理存储和取数据的结果。
通过上述方法,你可以轻松地在 Chrome 扩展中持久化保存并访问你的数据。如果你有更多关于 crxjs
的具体问题,可能需要查看它的文档以了解更多有关其包装和集成的详细内容。