A Look at the Channel Messaging API

Flavio Copes

Service Workers are isolated from the main JavaScript thread. Being a special kind of Web Worker, they share the same limitations. How do you communicate back to the main thread? Browsers offer us the Channel Messaging API. This API allows two scripts to communicate by passing simple messages on a shared channel.

It’s also useful to communicate with iframes, but we’ll focus on the worker use case in this post.

Instantiate the Channel

You can instantiate a channel using the following syntax:

const channel = new MessageChannel()

On the channel object, which is of type MessageChannel, you have access to the two ports, port1 and port2.

The gist is that at each end of the channel listen on one port, and you send messages to the other port.

When you create a channel, you send your messages to port2.

Sending Messages Through the Channel

You send a message through the channel using the postMessage() method, which is made available on the window object if the script is running in the browser:

const data = { color: 'green' }
const channel = new MessageChannel()
window.postMessage(data, [channel.port2])

Listen for Incoming Messages on the Receiving End

On the receiving end, in a Service Worker for example, you add a listener on self, a global that workers have to access themselves:

self.addEventListener('message', event => {
  console.log('Incoming message')
})

The event object passed as parameter contains the data attached to this event in the data property:

self.addEventListener('message', event => {
  console.log('Incoming message')
  console.log(event.data)
})

Send a Message Back

To send a message back, in the event listener we have access to the other port by referencing event.ports[0].

On this object we can call postMessage() and post back additional data:

self.addEventListener('message', event => {
  console.log('Incoming message')
  console.log(event.data)

  const data = { shape: 'rectangle' }
  event.ports[0].postMessage(data)
})

Receiving a Message as the Sender

The sender has access to the channel object it created, so it can attach an onmessage handler to the message.port1 object:

channel.port1.onmessage = event => {
  console.log(event.data)
}

What Kind of Messages Can You Send?

In postMessage() you can send any basic JavaScript data type. This means booleans, strings, numbers, and objects. You can use arrays to pass multiple objects.

  Tweet It

🕵 Search Results

🔎 Searching...