use "navigator.serviceWorker.controller.postMessage" it will alway "TypeError: Cannot read property 'postMessage' of null"
Asked Answered
P

1

2

I have the problem that after registering the service worker the navigator.serviceWorker.controller always is null.

I want to use postMessage to send a message to the service worker. However, navigator.serviceWorker.controller always returns null, and shows the error TypeError: Cannot read property 'postMessage' of null.

Sometimes I can use navigator.serviceWorker.controller.postMessage, but at other times navigator.serviceWorker.controller returns null, I am not sure how to deal with this issue...

I have done some research, but I still cannot fix my issue...

Has anybody any ideas?

Thanks, Terry

Here is the test page that I created. https://terrylee7788.github.io/test_web_worker.html

Portauprince answered 6/4, 2016 at 10:22 Comment(0)
W
8

Use navigator.serviceWorker.ready

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
  // Let's see if you have a subscription already
  return serviceWorkerRegistration.pushManager.getSubscription();
})
.then(function(subscription) {
  if (!subscription) {
    // You do not have subscription
  }
  // You have subscription.
  // Send data to service worker
  navigator.serviceWorker.controller.postMessage({'data': dataToServiceWorker});

})
Wanda answered 6/4, 2016 at 15:48 Comment(2)
That's unfortunately open to a race condition—the .ready promise can resolve before navigator.serviceWorker.controller is set. See github.com/slightlyoff/ServiceWorker/issues/799 which includes some workarounds.Emblements
The race condition that Jeff Posnick mentions means that conditioning on navigator.serviceWorker.ready is not a reliable solution. However, conditioning on his window._controlledPromise is reliable. Thanks @Jeff Posnick!Cottrill

© 2022 - 2024 — McMap. All rights reserved.