How do I cache data in Chrome Extension?

2020-03-12 11:41发布

问题:

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?

回答1:

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