如何在Chrome扩展程序中缓存数据? [英] How do I cache data in Chrome Extension?

查看:897
本文介绍了如何在Chrome扩展程序中缓存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我工​​作的库编写Chrome扩展程序。扩展程序每次打开时都会从库的API中获取最新的图书标题。



随着越来越多的人使用它,图书馆的服务器发送API数据。



在Chrome扩展程序中缓存数据的方式是什么? 例如,我会喜欢在第一次打开Chrome扩展程序时获取数据,然后保存它(不知道在哪里?),并且只有在1小时后,再向API请求并再次保存数据。



有人可以推荐一种在Chrome扩展程序中实现此功能的方法吗?

解决方案

对于本地存储,请使用 chrome.storage.local 。它有一个非常简单的API和5 MB的存储空间。



权限是storage您将授予您对 chrome.storage.local chrome.storage.sync 的访问权限。 本地为每个配置文件5 MB,保存在客户端上。 同步为100 KB,保存在Google帐户中。相同的API。



我发现 sync 是不可靠的,但您的需求似乎是<$ c $

  function fetchLive(callback){
doSomething(function(data){
chrome.storage.local.set({cache:data,cacheTime:Date.now()},function(){
回调(数据);
});
});


函数fetch(callback){
chrome.storage.local.get(['cache','cacheTime'],function(items){
if(items.cache& item.cacheTime&& item.cacheTime){
if(items.cacheTime> Date.now() - 3600 * 1000){
return callback( items.cache); //序列化是自动的,所以嵌套对象没有问题
}
}

fetchLive(callback);
});
}


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?

解决方案

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

这篇关于如何在Chrome扩展程序中缓存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆