My Chrome extension stores some data using chrome.storage
, & fetches the results from the storage as needed.
However, I realize now that I need to periodically need to refresh the data in chrome.storage
- which means clearing it from time to time.
Is it possible to:
Have Chrome treat chrome.storage
as Session storage - that is - it clears the data once the browser closes?
If above is not possible, is chrome.storage.remove
the only way to clear storage?
What happens when the chrome.storage
space hits its limit?
Store Date.now()
value with each object or alongside using a prefixed/suffixed key.
A separate key might be better if the objects are big.
Date.now() - CACHE_DURATION_IN_MS
remove()
and clear()
are the only methods to delete from 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.
Note: chrome.runtime.lastError
is undefined when no error occurred.
As you can see above, to ignore the default 5MB limit use "unlimitedStorage" permission.
Primitive example (a better one would use 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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With