Service Worker Introduction

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

Private messaging

In order for a Service Worker to message only with a specific page, we can use a message channel.

Code

// in page.html
const messageChannel = new MessageChannel();
messageChannel.port1.onmessage = event => { console.log('msg from SW', event); }
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
// in sw.js
this.addEventListener('message', event => {
  // do something
  event.ports[0].postMessage('private msg back');
});

Output

Reset all

Send your own message

The Service Worker will reply in Pig Latin.