//one-way communication
// app.js - Somewhere in your web app
navigator.serviceWorker.controller.postMessage({
type: 'MESSAGE_IDENTIFIER',
});
// service-worker.js
// On the Service Worker side we have to listen to the message event
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'MESSAGE_IDENTIFIER') {
// do something
}
});
//two-way communication.
//Using the Broadcast API
// app.js
// Set up channel
const broadcast = new BroadcastChannel('count-channel');
// Listen to the response
broadcast.onmessage = (event) => {
console.log(event.data.payload);
};
// Send first request
broadcast.postMessage({
type: 'INCREASE_COUNT',
});
// service-worker.js
// Set up channel with same name as in app.js
const broadcast = new BroadcastChannel('count-channel');
broadcast.onmessage = (event) => {
if (event.data && event.data.type === 'INCREASE_COUNT') {
broadcast.postMessage({ payload: ++count });
}
};
//Using the Client API
// app.js
// Listen to the response
navigator.serviceWorker.onmessage = (event) => {
if (event.data && event.data.type === 'REPLY_COUNT_CLIENTS') {
setCount(event.data.count);
}
};
// Send first request
navigator.serviceWorker.controller.postMessage({
type: 'INCREASE_COUNT_CLIENTS',
});
// service-worker.js
// Listen to the request
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'INCREASE_COUNT') {
// Select who we want to respond to
self.clients.matchAll({
includeUncontrolled: true,
type: 'window',
}).then((clients) => {
if (clients && clients.length) {
// Send a response - the clients
// array is ordered by last focused
clients[0].postMessage({
type: 'REPLY_COUNT',
count: ++count,
});
}
});
}
});