Handling Push Events in Service Worker
You'll learn how to listen for incoming push notifications in your service worker and extract the data they carry.
The Core Idea
Once a push subscription is active and your server sends a push message, your service worker receives it through a push event. This event fires even when your web app isn't open or visible—that's the magic of service workers working in the background. Your job is to listen for this event and handle the incoming data.
Think of it like a mail carrier delivering a package to your door while you're asleep. The service worker is always on duty, ready to receive and process messages even when the main application is dormant.
Listening for Push Events
In your service worker file, you register a listener for the push event:
self.addEventListener('push', function(event) {
// Handle the push event here
});
Accessing the Push Data Payload
The server can send data along with the push notification. Access it through event.data using methods like:
self.addEventListener('push', function(event) {
let notificationData = {};
if (event.data) {
notificationData = event.data.json(); // Parse JSON payload
// Or: event.data.text() for plain text
}
const title = notificationData.title || 'New Notification';
const options = {
body: notificationData.body,
icon: notificationData.icon
};
// You'll display the notification in the next step
console.log('Push received:', title);
});
The event.data object provides methods like .json(), .text(), .arrayBuffer(), and .blob() depending on how your server formats the payload.
Key Takeaway: The push event in your service worker lets you intercept incoming push messages and extract their data payload using event.data methods, enabling your PWA to respond to server notifications even when closed.