我的 Chrome 扩展程序使用 chrome.storage
存储一些数据,并根据需要从存储中获取结果。
但是,我现在意识到我需要定期刷新 chrome.storage
中的数据 - 这意味着不时清除它。
是否可以:
Chrome 是否将
chrome.storage
视为Session 存储 - 也就是说 - 一旦浏览器关闭它就会清除数据?如果上述方法不可行,
chrome.storage.remove
是清除存储空间的唯一方法吗?当
chrome.storage
空间达到极限时会发生什么?
最佳答案
将
Date.now()
值与每个对象一起存储,或者使用带前缀/后缀的键一起存储。
如果对象很大,单独的键可能会更好。- 定期检查所有项目并删除过期的项目,即存储日期小于当前
Date.now() - CACHE_DURATION_IN_MS
- 阅读时检查过期时间,需要时从网络(或其他地方)重新获取
- 定期检查所有项目并删除过期的项目,即存储日期小于当前
remove()
和clear()
是从 chrome.storage 中删除的唯一方法-
5,242,880 bytes: the maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError.
注意:当没有发生错误时,
chrome.runtime.lastError
是未定义的。 如上所示,要忽略默认的 5MB 限制,请使用 "unlimitedStorage"许可。
原始示例(更好的例子是使用 Promise):
function save(data, callback, retrying) {
Object.keys(data).forEach(k => data[k].savedOn = Date.now());
chrome.storage.local.set(data, () => {
if (!chrome.runtime.lastError)
return callback();
if (retrying)
throw chrome.runtime.lastError.message;
cleanup(() => save(data, callback, true));
});
}
const CACHE_DURATION = 7 * 24 * 3600 * 1000; // 7 days
function cleanup(callback) {
var cutoff = Date.now() - CACHE_DURATION;
chrome.storage.local.get(null, all => {
var expiredKeys = Object.keys(all).filter(k => all[k].savedOn < cutoff);
chrome.storage.local.remove(expiredKeys, callback);
});
}
关于javascript - 如何自动清除 chrome.storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42468802/