I'm writing Chrome Extension for library that I work at. The extension fetches the latest book titles from library's API every time it's opened.
As it gets used by more and more people it's putting big load on library's servers who send API data.
What would be the way to cache data in a Chrome Extension?
For example, I'd like to get the data the first time Chrome Extension is opened, then save it (not sure where?), and only after 1 hour has passed do request to API and save data again.
Can someone recommend a way to do this in Chrome Extension?
It provides the same storage capabilities as the localStorage API with the following key differences: User data can be automatically synced with Chrome sync (using storage. sync ). Your extension's content scripts can directly access user data without the need for a background page.
Navigate to chrome://version/ and look for Profile Path, it is your default directory and Extensions Folder is where all the extensions, apps, themes are stored. (If you have several browser profiles set up in Chrome, you will want to view the chrome://version/ page from the profile where the extension is installed.)
Clear your cache and browsing data with a single click of a button. Quickly clear your cache with this extension without any confirmation dialogs, pop-ups or other annoyances.
For local storage, use chrome.storage.local
. It has a very simple API and 5 MB of storage per profile.
The permission is "storage"
and it'll grant you access to chrome.storage.local
and chrome.storage.sync
. local
is 5 MB per profile, saved on the client. sync
is 100 KB, saved in the Google account. Same API.
I've found sync
to be unreliable, but your needs seem to be local
.
Usage:
function fetchLive(callback) {
doSomething(function(data) {
chrome.storage.local.set({cache: data, cacheTime: Date.now()}, function() {
callback(data);
});
});
}
function fetch(callback) {
chrome.storage.local.get(['cache', 'cacheTime'], function(items) {
if (items.cache && items.cacheTime && items.cacheTime) {
if (items.cacheTime > Date.now() - 3600*1000) {
return callback(items.cache); // Serialization is auto, so nested objects are no problem
}
}
fetchLive(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