簡體   English   中英

聯機后,后台同步不會刷新頁面

[英]Background sync doesn't refresh page when back online

最近,我開始學習有關服務人員,后台同步的信息...我實現了服務人員,在安裝步驟中,我緩存了一些要在脫機時顯示的文件。

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE)
      .then((cache) => {
        return cache.addAll([navigationIcon, offlineImage, offlineFallbackPage]);
      })
  );
});

我正在偵聽fetch事件,以在沒有互聯網連接時進行捕獲,因此那時我可以顯示離線頁面。

self.addEventListener('fetch', (event) => {
  if (event.request.mode === 'navigate' || (event.request.method === 'GET'
    && event.request.headers.get('accept')
      .includes('text/html'))) {
    event.respondWith(
      fetch(event.request.url)
        .catch(() => {
          // Return the offline page
          return caches.match(offlineFallbackPage);
        })
    );
  } else {
    event.respondWith(caches.match(event.request)
      .then((response) => {
        return response || fetch(event.request);
      }));
  }
});

我還添加了后台同步,因此可以在有互聯網連接時重新聯機。

注冊服務人員后,我添加了:

  .then(swRegistration => swRegistration.sync.register('backOnline'))

我在服務工作者中收聽同步事件。

當我離線並重新上網時,什么也沒發生。 但是,當我刪除提取事件(不顯示以前緩存的脫機頁面)時,頁面會自行返回在線狀態(當我有提取事件時,我想這樣做)

有人知道我應該添加些什么,以便我的頁面可以單獨返回在線狀態嗎?

您可以使用導航器,將其包括在已緩存的主js文件或服務工作人員js文件中,只需確保已將其緩存即可

let onlineStatus = locate => { 
  if(navigator.onLine){
    location.replace(locate)
  }
}
let isOfflinePage = window.location.pathname == offlineFallbackPage ? true : false;

// kindly edit isOfflinePage to return true if it's offline page

if(isOfflinePage){
  onlineStatus('index.html')
}

您可以簡單地使用location.reload()代替

暫無
暫無

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

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