I want to send a message to a service worker every time the page loads.
The first time the page loads it calls register() and then listens for the "controllerchange" event on navigator.serviceWorker but this never fires.
How do I know when I can start postMessaging a service worker?
navigator.serviceWorker.register(swURL).then(function(){
var sw;
if (navigator.serviceWorker.controller) {
sw = navigator.serviceWorker.controller;
sw.postMessage('ping');
return;
}
function onchange(){
sw = navigator.serviceWorker.controller;
sw.postMessage('ping');
navigator.serviceWorker.removeEventListener('controllerchange', onchange);
}
navigator.serviceWorker.addEventListener('controllerchange', onchange);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
How do I know when I can start postMessaging a service worker?
Just focusing on that bit: I'd recommend the following approach, which makes use of the navigator.serviceWorker.ready
promise:
// navigator.serviceWorker.ready can be used from anywhere in your
// page's JavaScript, at any time.
// It will wait until there's an active service worker,
// and then resolve with the service worker registration
navigator.serviceWorker.ready.then(registration => {
registration.active.postMessage('ping');
});
If you do want to get to the bottom of why your controllerchange
event listener isn't firing, my guess would be that you're not using clients.claim()
in your service worker's activate
event, which means the newly-activated service worker won't take control of the current page.
The reason it's not firing is because you are registering the controllerchange
event after the Service Worker has already installed/activated. So this event will fire for new Service Workers, e.g. ones that use skipWaiting()
. But not for the initial Service Worker.
Use navigator.serviceWorker.ready
promise which resolves as soon as there is an active Service Worker detected, no matter when it was installed/activated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With