title: Sending message from register service worker to client page
body: <p>I am trying to send a variable(boolean) to the app.js when the registration onupdatefound function is triggered , so whenever a new update is received the app.js will know and then i can show a popup with a refresh button.</p>
  <p>most of the part i have implemented , i am just confused as how my app.js will receive data on &quot;message&quot; addEventListener as i am not able to receive any data from it.</p>
  <p>thanking you in advance.</p>
  <blockquote>
  <p>registerServiceWorker.js</p>
  </blockquote>
  <pre><code>    registration.onupdatefound = () =&gt; {
       console.log('sw onupdatefound');
       const installingWorker = registration.installing;
        installingWorker.onstatechange = () =&gt; {
        console.log('sw onstatechange',navigator.serviceWorker);
        if (installingWorker.state === 'installed') {
          console.log('sw onstatechange//',navigator.serviceWorker);
  
          if (navigator.serviceWorker.controller) {
  
            // available; please refresh.&quot; message in your web app.
            console.log('New content is available; please refresh...');
  
            navigator.serviceWorker.controller.postMessage({
              data: {
                toUpdate: true,
              },
            });
  
          } else {
            console.log('Content is cached for offline use.');
          }
        }
      };
    };
  </code></pre>
  <blockquote>
  <p>service-worker.js</p>
  </blockquote>
  <pre><code>self.addEventListener('fetch', (event) =&gt; {
   console.log('in fetch of s-w');
  self.clients.matchAll().then(all =&gt; all.map(client =&gt; client.postMessage(event)));
  });
  
  self.addEventListener('message', (event) =&gt; {
   console.log('event msg from s-w', event.data);
  if (event.data.toUpdate) {
   console.log('updating');
  self.skipWaiting();
  }
  // Select who we want to respond to
  self.clients.matchAll().then(all =&gt; all.map(client =&gt; client.postMessage(event.data)));
  self.clients
   .matchAll({
     includeUncontrolled: true,
     type: 'window',
   })
  .then((clients) =&gt; {
    clients.postMessage(event.data);
    if (clients &amp;&amp; clients.length) {
      // Send a response - the clients
      // array is ordered by last focused
      clients[0].postMessage(event.data);
    }
   });
  });
  </code></pre>
  <blockquote>
  <p>app.js</p>
  </blockquote>
  <pre><code>navigator.serviceWorker.onmessage = (event) =&gt; {
   console.log('event in app.js nav on msg', event);
   if (event.data.toUpdate) {
    alert('Please refresh your page to upadate service worker');
   }
  };
  
  window.addEventListener('message', (event) =&gt; { console.log('new event ====&gt;', event); });
  </code></pre>