簡體   English   中英

如何在Progressive Web Apps的瀏覽器中存儲脫機存儲永久數據?

[英]How to store offline Storage permanent data inside browser in Progressive Web Apps?

是否可以在瀏覽器內部的離線存儲中存儲永久數據? 如果有任何解決方案,那么請幫助我,以便我可以解決我的問題。 我閱讀了一些教程,但這對我沒有用。 提前致謝!

讓我們直接提出離線存儲數據的一般建議:

  • 對於脫機時加載應用程序所需的網絡資源,請使用Cache API(服務工作者的一部分)。
  • 對於所有其他數據,請使用IndexedDB(帶有promises包裝器)。

在告訴您每個瀏覽器的存儲限制后,我將告訴您如何使用兩者。

  • 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,並且大小和類型(僅字符串)受限制。 [教學課程]
  • 還有其他一些,但並沒有得到廣泛支持,而且非常困難

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM