javascript - 如何自动清除 chrome.storage

标签 javascript google-chrome google-chrome-extension

我的 Chrome 扩展程序使用 chrome.storage 存储一些数据,并根据需要从存储中获取结果。

但是,我现在意识到我需要定期刷新 chrome.storage 中的数据 - 这意味着不时清除它。

是否可以:

  1. Chrome 是否将 chrome.storage 视为Session 存储 - 也就是说 - 一旦浏览器关闭它就会清除数据?

  2. 如果上述方法不可行,chrome.storage.remove 是清除存储空间的唯一方法吗?

  3. chrome.storage 空间达到极限时会发生什么?

最佳答案

  1. Date.now() 值与每个对象一起存储,或者使用带前缀/后缀的键一起存储。
    如果对象很大,单独的键可能会更好。

    • 定期检查所有项目并删除过期的项目,即存储日期小于当前 Date.now() - CACHE_DURATION_IN_MS
    • 阅读时检查过期时间,需要时从网络(或其他地方)重新获取
  2. remove()clear() 是从 chrome.storage 中删除的唯一方法

  3. 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 是未定义的。

  4. 如上所示,要忽略默认的 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/

相关文章:

php - 为什么 google chrome 和 IE 会出现这种奇怪的行为?

html - 如何关闭 iphone chrome 模拟器中的蓝色覆盖?

javascript - Chrome 扩展 XMLHttpRequest 使用 HTTPS 和非常规端口返回 0

javascript - Chrome 时间轴缓冲区使用情况

javascript - 如何根据路线重用具有不同变量的AngularJS Controller

javascript - Firefox 使用鼠标 x,y 的方法与 Chrome 或 IE 不同

javascript - 如何在扩展 Chrome DevTool 时检索请求的发起者?

javascript - 使用 toBlob 下载 Canvas 图像

java - 如何从 chromecast android 获取播放和停止事件回调

javascript - 在 Chrome 扩展中使用图像 Sprite 有意义吗?