when you register a service worker it returns a promise, that promise is resolved with a "service worker registration object"
navigator.serviceWorker.register('/sw.js').then(reg => {
// registration object methods
// reg.unregister()
// reg.update()
})
// reg.installing - means an update is on its way
// reg.waiting - updated service worker ready and waiting to take over
// reg.active -
updatefound
when this event is emitted the service worker that was installing is now the new worker
reg.addEventListener('updatefound', () => {
// reg.intstalling
})
const sw = reg.installing
console.log(sw.state)
// this can be one of the following
// "installed" - install completed but not acitivated
// "activating" - activating event has fired but not yet completed
// "activated" - activating completed and ready to receive fetch events
// "redundant" - sw has been thrown away, when old sw is replaced by a new sw.addEventListener('statechange', () => {
// this event is emitted when the value of the service worker's state property has changed
})
navigator.serviceworker.controller
navigator.serviceWorker.register('/sw.js').then(reg => {
// registration object methods
// reg.unregister()
// reg.update()
})
if (!navigator.serviceworker.controller) {
// the page did not load using a service worker so return early
}
if (reg.waiting) {
// there's an update to the service worker and it's waiting to be used
// here we would want to let the user know, through some UI element that there's an update ready.
}
if (reg.installing) {
// there's a service worker update in-progress, or installing
// since this could fail we want to listent to the statechange event
reg.installing.addEventListener('statechange', () => {
if (this.state === 'installed') {
// there's an update ready, let the user know
}
})
}
reg.addEventListener('updatefound', () => {
reg.installing.addEventListener('statechange', () => {
if (this.state === 'installed') {
// there's an update ready let the user know
}
})
})
use this on click of the refresh button we show to the user
self.skipWaiting()
from a page
reg.installing.postMessage({ foo: 'bar' })
from the service worker
self.addEventListener('message', event => {
event.data; // { foo: 'bar' }
})
navigator.serviceWorker.addEventListener('controllerchange', () => {
// navigator.serviceWorker.controller has changed
})