首页 > 解决方案 > 如何在 Progressive Web Apps 中的浏览器内存储离线存储永久数据?

问题描述

是否可以将永久数据存储在浏览器内的离线存储中?如果有任何解决方案,请帮助我,以便我可以解决我的问题。我读了一些教程,但这对我没有用。提前致谢!

标签: javascriptjqueryangularjsreactjsprogressive-web-apps

解决方案


让我们直接提出关于离线存储数据的一般建议:

  • 对于离线加载应用所需的网络资源,请使用缓存 API(服务工作者的一部分)。
  • 对于所有其他数据,请使用 IndexedDB(带有 Promise 包装器)。

在我告诉你每个浏览器的存储限制后,我会告诉你如何使用这两者。

  • Chrome 支持使用 <6% 的可用空间
  • Firefox 支持使用 <10% 的可用空间
  • Safari 支持使用 <50MB
  • Internet Explorer 10 支持使用 <250MB
  • 使用 Edge,它取决于卷大小

使用缓存 api 的服务工作者的工作示例是

var CACHE_VERSION = 1;

// Shorthand identifier mapped to specific versioned cache.
var CURRENT_CACHES = {
  font: 'font-cache-v' + CACHE_VERSION
};

self.addEventListener('activate', function(event) {
  var expectedCacheNames = Object.values(CURRENT_CACHES);

  // Active worker won't be treated as activated until promise
  // resolves successfully.
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (!expectedCacheNames.includes(cacheName)) {
            console.log('Deleting out of date cache:', cacheName);

            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(

    // Opens Cache objects that start with 'font'.
    caches.open(CURRENT_CACHES['font']).then(function(cache) {
      return cache.match(event.request).then(function(response) {
        if (response) {
          console.log('Found response in cache:', response);

          return response;
        }

        console.log('Fetching request from the network');

        return fetch(event.request).then(function(networkResponse) {
          cache.put(event.request, networkResponse.clone());

          return networkResponse;
        });
      }).catch(function(error) {

        // Handles exceptions that arise from match() or fetch().
        console.error('Error in fetch handler:', error);

        throw error;
      });
    })
  );
});

【来源与解释】

而且我不确定如何使用 IndexedDB 其他一些方法是

  • 仅适用于 Chrome 13+、Edge、Firefox 50+ 和 Opera 15+ 的文件系统 API [教程]
  • Web 存储(例如 LocalStorage 和 SessionStorage)是同步的,不支持 Web Worker,并且大小和类型(仅限字符串)有限。[教程]
  • 还有其他但没有得到广泛支持并且非常困难

推荐阅读