基本上,我试图在检测到新的 serviceworker 版本时显示一个对话框,然后让用户决定重新加载以获取它。为此,我们需要skipWaiting
在重新加载窗口之前主动设置。
这是我的行动:
onClickHandler = () => {
console.log('on click', 'posting skipWaiting');
navigator.serviceWorker.controller.postMessage('skipWaiting');
};
这是我创建 eventListener 的尝试:
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
console.log('worker state', installingWorker.state);
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.'
);
navigator.serviceWorker.addEventListener('message', event => {
console.log('skip waiting');
if (event.data === 'skipWaiting') {
self.skipWaiting();
}
});
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
问题是navigator.serviceWorker.addEventListener('message', event =>
不会被触发。我是在声明听众错了吗?