简体   繁体   English

如何在Chrome扩展程序中缓存数据?

[英]How do I cache data in Chrome Extension?

I'm writing Chrome Extension for library that I work at. 我正在为我工​​作的图书馆编写Chrome扩展程序。 The extension fetches the latest book titles from library's API every time it's opened. 该扩展程序每次打开时都会从库的API中获取最新的书名。

As it gets used by more and more people it's putting big load on library's servers who send API data. 随着越来越多的人使用它,它会对发送API数据的库的服务器造成很大的负担。

What would be the way to cache data in a Chrome Extension? 在Chrome扩展程序中缓存数据的方法是什么?

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. 例如,我想首次打开Chrome扩展程序时获取数据,然后将其保存(不知道在哪里?),并且仅在经过1小时后才向API请求并再次保存数据。

Can someone recommend a way to do this in Chrome Extension? 有人可以推荐一种方法在Chrome扩展程序中执行此操作吗?

For local storage, use chrome.storage.local . 对于本地存储,请使用chrome.storage.local It has a very simple API and 5 MB of storage per profile. 它有一个非常简单的API和每个配置文件5 MB的存储空间。

The permission is "storage" and it'll grant you access to chrome.storage.local and chrome.storage.sync . 权限是"storage" ,它将授予您访问chrome.storage.localchrome.storage.sync local is 5 MB per profile, saved on the client. local每个配置文件5 MB,保存在客户端上。 sync is 100 KB, saved in the Google account. sync为100 KB,保存在Google帐户中。 Same API. 相同的API。

I've found sync to be unreliable, but your needs seem to be local . 我发现sync不可靠,但你的需求似乎是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);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM