我想测试我的服务工作者的多个状态,但我的ns0:
事件为空:
onstatechange
如果我记录了if (navigator.serviceWorker.controller) {
console.log("[PWA] Active Service Worker found, no need to register");
} else {
// Register the ServiceWorker
navigator.serviceWorker
.register("{{ path('sw.js')|raw }}", { scope: "{{ path('homepage')|raw }}" })
.then(reg => {
if (!reg.installing) {
return;
}
const worker = reg.installing;
const { state } = worker;
console.log(worker);
worker.addEventListener("onstatechange", () => {
console.log('testtt');
switch (true) {
case state === "installing":
console.log("[PWA] Service Worker is installing...");
break;
case state === "installed":
console.log("[PWA] Service Worker Install successful");
break;
case state === "redundant":
console.log("[PWA] Service Worker Install failed");
break;
case state === "activated" && !navigator.serviceWorker.controller:
console.log('[PWA] Service Worker is offline')
// Show an offline style
// showOfflineToast();
break;
}
});
})
.catch(error => console.log(`[PWA] Error during service worker registration : ${error}`));
}
,那么它只是state
状态。
答案 0 :(得分:0)
您应该将switch语句更改为此
I hope the tour went well, Mr. Wonka.
答案 1 :(得分:0)
您的if (!reg.installing)
条件导致代码块过早退出。试试这个:
navigator.serviceWorker
.register("{{ path('sw.js')|raw }}", { scope: "{{ path('homepage')|raw }}"
.then(reg => {
const sw = reg.installing || reg.waiting || reg.active;
if (sw) {
logSwState(sw.state)
sw.addEventListener('statechange', function(e) {
logSwState(e.target.state);
})
}
})
// logs Service Worker state to console
function logSwState(swState) {
switch (swState) {
case 'installing':
console.log('[PWA] Service Worker state: installing');
break;
case 'installed':
console.log('[PWA] Service Worker state: installed');
break;
case 'activating':
console.log('[PWA] Service Worker state: activating');
break;
case 'activated':
console.log('[PWA] Service Worker state: activated');
break;
case 'redundant':
console.log('[PWA] Service Worker state: redundant');
break;
default:
console.log('[PWA] Service Worker state: UNKNOWN');
}
}