How to cache data in Chrome Extension?

I am writing a Chrome extension for the library in which I work. The extension retrieves the latest book titles from the library API every time it opens.

As it becomes more and more popular, it places a heavy strain on library servers that send API data.

How can I cache data in the Chrome extension?

For example, I would like to get the data the first time I open the Chrome extension, and then save it (not sure where?), And only after 1 hour has passed, an API request and saving the data again.

Can someone recommend a way to do this in Chrome Extension?

+5
source share
1 answer

For local storage, use chrome.storage.local . It has a very simple API and 5 MB of memory for each profile.

The permission is "storage" and it will give you access to chrome.storage.local and chrome.storage.sync . local - 5 MB per profile stored on the client. sync - sync saved in your Google account. The same API.

I found sync unreliable, but your needs look like local .

Using:

 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); }); } 
+7
source

All Articles