Service Worker Introduction

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

Service Worker to pages

A Service Worker can control many pages at the same time. From within the Service Worker you can list all connected clients (which include our pages) and send them a message. However this is only suitable when you want to broadcast a message to all of them.

Code

// in sw.js
this.clients.matchAll().then(clients => {
  clients.forEach(client => client.postMessage('hello from the other side'));
});
// in page.html
window.addEventListener('message', event => { console.log(event.data) }, false);

The Service Worker will broadcast a message when receiving a push or message. Emulate a push (via the DevTools > Resources > Service Workers > bell icon) or trigger a message via this button:

Output

Reset all