![](/img/trans.png)
[英]Workbox - Background Sync - Offline Post - Replay Events when the browser is back online doesn't get triggered
[英]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.