我目前正在将最新的Workbox版本4.3.1与workbox-window
一起使用,我正在通过监听waiting
事件为用户提供页面重新加载,我正在使用提供的代码Workbox文档的Advanced Recipes页。
页面上的代码:
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
// Add an event listener to detect when the registered
// service worker has installed but is waiting to activate.
wb.addEventListener('waiting', (event) => {
// `event.wasWaitingBeforeRegister` will be false if this is
// the first time the updated service worker is waiting.
// When `event.wasWaitingBeforeRegister` is true, a previously
// updated same service worker is still waiting.
// You may want to customize the UI prompt accordingly.
// Assumes your app has some sort of prompt UI element
// that a user can either accept or reject.
const prompt = createUIPrompt({
onAccept: async () => {
// Assuming the user accepted the update, set up a listener
// that will reload the page as soon as the previously waiting
// service worker has taken control.
wb.addEventListener('controlling', (event) => {
window.location.reload();
});
// Send a message telling the service worker to skip waiting.
// This will trigger the `controlling` event handler above.
// Note: for this to work, you have to add a message
// listener in your service worker. See below.
wb.messageSW({type: 'SKIP_WAITING'});
},
onReject: () => {
prompt.dismiss();
}
})
});
wb.register();
}
服务工作者文件中的代码:
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
我已经对其进行了测试,并且可以正常工作,我可以向用户显示一个小吃栏,让他们知道有更新,并且当他们接受时,会向服务人员发送SKIP_WAITING
消息以致电{ {1}}。
让我们假设用户不接受重新加载提示并刷新页面或导航到另一个页面,新的服务工作者将一直等待并且不会被激活,这是正常现象,但是我的问题是我该如何解决?在用户刷新或导航到另一个页面时向用户显示此重新加载提示?看来skipWaiting()
事件仅触发一次。