Search code examples
google-chromeprogressive-web-appsservice-workermessaging

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


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


Solution

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