Javascript 检查ServiceWorker是否处于等待状态
我试图理解服务工作者API,并且我知道关于注册服务工作者的一些细节 如API文档中所述,如果发现服务工作者更新,则会注册该服务工作者并将其添加到队列中。当且仅当页面关闭并再次打开时,此软件才会接管页面。也就是说,窗口关闭并再次打开 现在,这有几个缺点:Javascript 检查ServiceWorker是否处于等待状态,javascript,progressive-web-apps,service-worker,wait,Javascript,Progressive Web Apps,Service Worker,Wait,我试图理解服务工作者API,并且我知道关于注册服务工作者的一些细节 如API文档中所述,如果发现服务工作者更新,则会注册该服务工作者并将其添加到队列中。当且仅当页面关闭并再次打开时,此软件才会接管页面。也就是说,窗口关闭并再次打开 现在,这有几个缺点: 用户可能看到以前的版本可能有非常严重的语法错误,或者其他什么 需要以某种方式通知用户内容已更改,并且referesh会这样做 我知道如何把SW.js告诉skipWaiting()并接管。我还知道如何向SW.js发送消息,告诉它用户希望自动刷新
SW.js
告诉skipWaiting()
并接管。我还知道如何向SW.js
发送消息,告诉它用户希望自动刷新
然而,我不知道的是如何知道一个新软件是否实际处于等待状态
我用过这个:
navigator.serviceWorker.ready.then((a) => {
console.log("Response, ", a);
if (a.waiting !== null && a.waiting.state === "installed") {
console.log("okay");
}
});
但是,它通常将等待状态返回为null
(可能是因为在触发请求时软件仍在安装。)
我如何才能在客户端页面上知道等待的服务人员是否可用?以下是一些代码,每当有新的或更新的服务人员注册时,这些代码将检测并允许您处理各种状态 请注意,日志消息假定在服务人员安装期间未调用
skipWaiting()
;如果正在调用它,那么它将自动激活,而不必关闭所有选项卡来激活新的服务人员
if ('serviceWorker' in navigator) {
window.addEventListener('load', async function() {
const registration = await navigator.serviceWorker.register('/service-worker.js');
if (registration.waiting && registration.active) {
// The page has been loaded when there's already a waiting and active SW.
// This would happen if skipWaiting() isn't being called, and there are
// still old tabs open.
console.log('Please close all tabs to get updates.');
} else {
// updatefound is also fired for the very first install. ¯\_(ツ)_/¯
registration.addEventListener('updatefound', () => {
registration.installing.addEventListener('statechange', () => {
if (event.target.state === 'installed') {
if (registration.active) {
// If there's already an active SW, and skipWaiting() is not
// called in the SW, then the user needs to close all their
// tabs before they'll get updates.
console.log('Please close all tabs to get updates.');
} else {
// Otherwise, this newly installed SW will soon become the
// active SW. Rather than explicitly wait for that to happen,
// just show the initial "content is cached" message.
console.log('Content is cached for the first time!');
}
}
});
});
}
});
}
这太棒了。不过,我应该亲自检查这些文件。无论如何,谢谢。杰夫,我似乎在你的代码中发现了一个错误:“等待”不是服务工作者的有效状态(“安装”、“安装”、“激活”、“激活”和“冗余”是服务工作者的有效状态)。”等待(以及“安装”和“活动”)是注册的属性,而不是服务人员。谢谢;我最近一直在使用,将更新我的旧答案。@JeffPosnick正在检查哪里定义了
updatedSW
?对不起,这是早期版本的遗留问题。我已将其切换为使用event.target
。