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.
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
.
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])
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)
})
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)
})
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)
}
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.
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.
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!