Hemanth's Scribes

web

ServiceWorker Communication via MessageChannel

Author Photo

Hemanth HM

Thumbnail

Two-way communication between ServiceWorker and main thread is easily possible with MessageChannel API.

In app.js

Create a sendMessage method:

function sendMessage(message) {
  return new Promise((resolve, reject) => {
    const messageChannel = new MessageChannel();
    
    messageChannel.port1.onmessage = function(event) {
      resolve(`Received a direct message from the ServiceWorker: ${event.data}`);
    };
    
    navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2])
  });
}

## In sw.js

Receive and respond to the message:
javascript
self.addEventListener('message', function(event) {
  console.log(`Received a message from main thread: ${event.data}`);
  event.ports[0].postMessage(`Roger that! - "${event.data}"`);
});

Usage

From your app.js, send a message and get a response:

var log = console.log.bind(console);
var error = console.error.bind(console);

sendMessage('hello').then(log, error).catch(error);

This would log:

Received message from main thread: Hello
Received direct message from service worker: Roger that! - "Hello"
#javascript#service-worker#web-api
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.