问题描述
我正在使用这种众所周知的模式在准备安装 Service Worker 更新时显示通知(此代码进入网页,当然不是 Service Worker 代码):
// Register service worker.
let newWorker;
if ('serviceWorker' in navigator) {
function showUpdateNotification () {
document.getElementById('updatenotification').style['visibility'] = 'visible';
};
window.addEventListener('load',() => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('Service worker registered at scope "' + registration.scope + '".');
// The commented code below is needed to show the notification after a page reload.
//
// if (registration.waiting) {
// console.log('Service working in skipwaiting state.');
// showUpdateNotification();
// }
registration.onupdatefound = () => {
console.log('Service worker update found.');
console.log('Installing service worker is',registration.installing);
newWorker = registration.installing;
newWorker.onstatechange = function () {
console.log('Service worker state changed to',newWorker.state);
if (newWorker.state == 'installed' && navigator.serviceWorker.controller) {
console.log('New service worker is ready to install on refresh.');
showUpdateNotification();
}
};
};
console.log('Updating service worker.');
registration.update();
}).catch(error => console.log('Service worker not registered (' + error +').'))
})
}
当然,该代码有效,因为它会在准备安装新版本的 Service Worker 时在网页上显示通知。
问题在于,如果此时页面重新加载,则不再显示通知,因为如果安装了新的 Service Worker 并等待激活,则不再触发 updatefound
事件。>
因此,通知只出现ONCE,当新的 Service Worker 安装并等待激活并开始控制页面时,但是一旦页面重新加载,通知就消失了。
我已经通过使用注释代码解决了这个问题:
// The commented code below is needed to show the notification after a page reload.
//
// if (registration.waiting) {
// console.log('Service working in skipwaiting state.');
// showUpdateNotification();
// }
此代码在注册时检查是否有某个 Service Worker 处于等待状态并再次显示通知。
我的问题是:这是正确的吗?我可以安全地使用那个“技巧”还是我在打电话给麻烦?
我是 Service Worker 的新手,所以我不确定我是否可以做这种事情。
提前致谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)