Tutorial

A Look at the Channel Messaging API

Updated on April 16, 2020
author

Flavio Copes

A Look at the Channel Messaging API

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 our products

About the authors
Default avatar
Flavio Copes

author

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
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 below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.