diff --git a/index.ts b/index.ts index 920a12c..8af315b 100644 --- a/index.ts +++ b/index.ts @@ -102,8 +102,12 @@ async function deleteWithLogic(logic?: (x: CacheItem) => boolean): Promis } } +let lastRun = 0; // Homemade debouncing due to `chrome.alarms` potentially queueing this function async function deleteExpired(): Promise { - await deleteWithLogic(cachedItem => Date.now() > cachedItem.maxAge); + if (lastRun < Date.now() - 1000) { + lastRun = Date.now(); + await deleteWithLogic(cachedItem => Date.now() > cachedItem.maxAge); + } } async function clear(): Promise { @@ -163,13 +167,24 @@ const cache = { }; function init(): void { + // Make it available globally for ease of use + (window as any).webextStorageCache = cache; + // Automatically clear cache every day - if (isBackgroundPage()) { + if (!isBackgroundPage()) { + return; + } + + if (chrome.alarms) { + chrome.alarms.create('webext-storage-cache', { + delayInMinutes: 1, + periodInMinutes: 60 * 24 + }); + chrome.alarms.onAlarm.addListener(deleteExpired); + } else { setTimeout(deleteExpired, 60000); // Purge cache on launch, but wait a bit setInterval(deleteExpired, 1000 * 3600 * 24); } - - (window as any).webextStorageCache = cache; } init(); diff --git a/readme.md b/readme.md index 19f3973..1cb80af 100644 --- a/readme.md +++ b/readme.md @@ -19,14 +19,21 @@ import storageCache from 'webext-storage-cache'; ## Usage -This module requires the `storage` permission: +This module requires the `storage` permission and it’s suggested to also use `alarms` to safely schedule cache purging: -```json -// manifest.json +```json5 +/* manifest.json */ { "permissions": [ - "storage" - ] + "storage", + "alarms" + ], + "background": { + "scripts": [ + /* Remember to include/import it in the background to enable expired cache purging */ + "webext-storage-cache.js" + ] + } } ``` @@ -45,7 +52,7 @@ import cache from 'webext-storage-cache'; })(); ``` -The same code could be also written more effectively with `cache.function`: +The same code could also be written more effectively with `cache.function`: ```js import cache from 'webext-storage-cache';