Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't pass data to serviceWorker once it's registered as it's null

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'});

})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading