'How can I detect if a serviceworker install fails?
My serviceworker is partially generated by gulp, so there's some chance it ends up with a SyntaxError or TypeError if I've made a mistake, and I'd like to be about to detect in my navigator.serviceWorker.register code that this has occurred, and send an error report.
I haven't figured out how to do this. I figured there'd be some sort of "on fail" event but I haven't found one. It looks like maybe I'm looking for an SW with a redundant state...
I tried
const newWorker = reg.installing
newWorker.addEventListener('statechange', () => {
if (newWorker.state == 'redundant') {
// log error
}
})
but the condition doesn't seem to fire. This condition also doesn't fire:
reg.addEventListener('updatefound', () => {
if (reg.redundant) {
// log error
}
})
I don't see any examples in the SW tutorials of this, which is surprising since it seems like a sort of basic thing to want to notice and detect.
Solution 1:[1]
If there's a syntax error, or if your service worker contains anything that is invalid JavaScript, your call to navigator.serviceWorker.register() will reject. (It might also reject if there's a network error preventing the script from being downloaded.)
If your service worker contains valid JavaScript but throws a runtime exception prior to finishing the install step, then the service worker will transition from the installing state to redundant. Note that in this scenario, navigator.serviceWorker.register() will not reject, as the redundant state transition happens after the registration has succeeded.
navigator.serviceWorker.register('sw.js')
.then((reg) => {
// reg.installing may or may not be set, depending on whether
// a new SW was registered.
reg.installing?.addEventListener('statechange', (event) => {\
if (event.target.state === 'redundant') {
// There was a runtime error.
}
});
})
.catch((err) => console.log('SW registration failed:', err));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff Posnick |
