O'Reilly logo

Building Progressive Web Apps by Tal Ater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 8. Service Worker to Page Communication with Post Messages

As we move more and more logic away from the page and into the service worker, we often find ourselves needing to communicate between the two.

In Chapter 7, we saw how moving important events such as network requests away from the volatile page unto the service worker can make our apps more reliable. But we often need to update our pages based on the results of those actions. For example, in “Adding Background Sync to Our App”, we moved the code that makes new registrations to a background sync event that runs in the service worker. This event calls the server and receives in response a JSON file containing the updated reservation details. We are using the data in that JSON file to update the reservation details in IndexedDB, but as the service worker doesn’t have access to the window, we were unable to update the details of the reservation in the DOM. Instead, the page relies on a naïve setInterval() that checks the network for the reservation’s status every few seconds and updates the DOM. If our sync event could send the updated reservation details to the page as soon as they are received, we could update the DOM immediately and avoid making this needless network request.

In this chapter, we will see how we can use postMessage() to send messages and data back and forth between the page and service worker and explore several types of communication:

  • Sending a message from the window to the service worker that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required