I’m new with serviceWorker and trying to pass data to it after it’s registered a way like
navigator.serviceWorker.register('/serviceWorker.js').then(function () {
navigator.serviceWorker.controller.postMessage({'hello': 'world'});
});
But I receive the error
Cannot read properties of null (reading ‘postMessage’)
>Solution :
You can wait until service worker is ready and then post a message
like this :
if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js');
navigator.serviceWorker.ready.then( registration => {
registration.active.postMessage({'hello': 'world'});
});
}
or if you want to use controller you can do it in this way :
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
// Let's see if you have a subscription already
return serviceWorkerRegistration.pushManager.getSubscription();
})
.then(function(subscription) {
if (!subscription) {
return;
}
navigator.serviceWorker.controller.postMessage({'hello': 'world'});
})