As part of my ongoing series on service workers, we looked at how to save pages for offline viewing as a user visits them and how to cache files with an expiration date.
Today, we’re going to build on that feature by looking at how to trigger service worker behaviors from the front end.
message
event #The service worker API includes a postMessage()
method.
This method creates an event that your service worker can listen for and respond to.
navigator.serviceWorker.controller.postMessage('hi');
In your service worker, you can listen for the message
event with the addEventListener()
method.
The event.data
property contains the argument you passed in to the postMessage()
method.
// If the "hi" message is posted, say hi back
self.addEventListener('message', function (event) {
if (event.data !== 'hi') return;
console.log('Oh, hi there!');
});
The data you pass in to postMessage()
isn’t limited to just strings.
You can pass in arrays and objects (anything that can be JSON.stringify()
-ed) too. You don’t need to stringify or parse them. The API handles that for you automatically.
navigator.serviceWorker.controller.postMessage({
type: 'hi',
name: 'Dave',
greeting: 'Hello there'
});
// If the "hi" message is posted, say hi back
self.addEventListener('message', function (event) {
if (event.data.type !== 'hi') return;
console.log(`${event.data.greeting}, ${event.data.name}!`);
});
#function