简体   繁体   English

联机后,后台同步不会刷新页面

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

recently I started learning about service workers, background syncs... I implemented service worker and in install step I cached some files I want to show when offline. 最近,我开始学习有关服务人员,后台同步的信息...我实现了服务人员,在安装步骤中,我缓存了一些要在脱机时显示的文件。

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

I am listening to fetch event to catch when there is no internet connection so I can show offline page when then. 我正在侦听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);
      }));
  }
});

I also added background sync, so I can go back online when there is internet connection. 我还添加了后台同步,因此可以在有互联网连接时重新联机。

After registering service worker I added: 注册服务人员后,我添加了:

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

And I listen to sync event in my service worker. 我在服务工作者中收听同步事件。

When I'm offline and go back online nothing happens. 当我离线并重新上网时,什么也没发生。 BUT when I delete my fetch event (don't show previously cached offline page) then page goes back online by itself (which I want to do when I have fetch event) 但是,当我删除提取事件(不显示以前缓存的脱机页面)时,页面会自行返回在线状态(当我有提取事件时,我想这样做)

Does anyone know what should I add so my page can go back online by itself? 有人知道我应该添加些什么,以便我的页面可以单独返回在线状态吗?

You can use navigator, Include it in your main js file that is cached or in your service-worker js file, just ensure it's cached 您可以使用导航器,将其包括在已缓存的主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')
}

You can simply use location.reload() instead 您可以简单地使用location.reload()代替

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

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