Service Worker Introduction

Step-by-step introduction to the Service Worker API.

Page to Service Worker

A page can communicate with the Service Worker its controlled by, by sending messages. The page can access that Service Worker via navigator.serviceWorker.controller and use postMessage() to send a message it.

Code

// in page.html
navigator.serviceWorker.controller.postMessage({'hello':'world'});
// in sw.js
this.addEventListener('message', event => {
  console.log(event.data); // outputs {'hello':'world'}
});

Note: the Service Worker needs to be activated to take control of the page. So you may need to refresh this page first.

Send your own message

Output

Reset all