Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cache data in Chrome Extension?

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?

like image 423
bodacydo Avatar asked Aug 01 '15 21:08

bodacydo


People also ask

Can a Chrome extension store data?

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.

Where are Chrome extension data stored?

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.)

What is clear cache extension?

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.


1 Answers

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);
  });
}
like image 135
Rudie Avatar answered Sep 19 '22 19:09

Rudie