Monday, October 24, 2022

Sending Message From and To The Service Worker

 


In this post we will review how to send messages from a service worker to the page javascript, and how to send messages from the page javascript back to the service worker.


See also the related posts:

Send a message from the page to the service worker

First we send a message from the page:


const event = {
type: "hello-from-page",
data: "this is my data",
}
navigator.serviceWorker.controller.postMessage(event)

Notice that the data is sent to the page related service worker. It is not possible to send the message to another site/page service worker, but only to the page location service worker.

The service worker should accept the message.


self.addEventListener('message', (event) => handleMessageFromPage(event))

function handleMessageFromPage(event) {
if (event.data.type === 'hello-from-page' ) {
console.log(event.data.data)
}
}

As the service worker is single threaded, make sure to handle the message in a timely fashion.


Send a message from the service worker to the page


The service worker can send a response directly to the page which sent the message, or alternatively send notification to all of the connected pages.


function notifyReadyForClients() {
self.clients.matchAll().then((clients) => {
for (const client of clients) {
console.log(`notifying client ${client.id} - ${client.url}`)
client.postMessage('this is the message from the service worker')
}
})
}


The page receives the message back using the following:


navigator.serviceWorker.addEventListener('message', receiveMessageFromServiceWorker)

function receiveMessageFromServiceWorker(event) {
if (event.data === 'this is the message from the service worker') {
console.log(`got ready notification from service worker`)
}
}



Final note

Working with service workers add many abilties to the web application, however, it might complicate the development and testing cycles. It is important to use a well design architecture for messaging between the service worker and the page, and avoid a spaghetti messaging design.


No comments:

Post a Comment