// Tutorial //

A Look at the Channel Messaging API

Published on September 3, 2018 · Updated on April 16, 2020
Default avatar
By Flavio Copes
Developer and author at DigitalOcean.
A Look at the Channel Messaging API

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click here to Sign up and get $200 of credit to try our products over 60 days!