Notification Actions and Click Handling
You'll learn how to add interactive buttons to push notifications and respond when users click them or the notification itself.
The Core Idea
Once you've displayed a notification using showNotification(), you can make it interactive. You add action buttons that let users respond directly from the notification (like "Reply" or "View"), and you listen for events in your service worker to handle those interactions—whether the user clicks an action button, the notification body, or closes it entirely.
Think of it like a mini-menu attached to your notification: instead of just passively reading a message, users can take immediate action without opening your app.
Adding Action Buttons
When calling showNotification(), pass an actions array in the options:
self.registration.showNotification('New Message', {
body: 'You have a new message from Alice',
icon: '/icon.png',
actions: [
{ action: 'reply', title: 'Reply', icon: '/reply-icon.png' },
{ action: 'view', title: 'View', icon: '/view-icon.png' }
]
});
Each action has an action identifier, a title label, and optionally an icon.
Handling Clicks
Listen for the notificationclick event in your service worker:
self.addEventListener('notificationclick', (event) => {
event.notification.close();
if (event.action === 'reply') {
// Handle reply action
event.waitUntil(clients.openWindow('/reply'));
} else if (event.action === 'view') {
// Handle view action
event.waitUntil(clients.openWindow('/messages'));
} else {
// User clicked notification body (no action specified)
event.waitUntil(clients.openWindow('/'));
}
});
You can also handle notificationclose if you need to track dismissals.
Key Takeaway: Notification actions create interactive buttons with unique identifiers, and the notificationclick event lets you route users to specific pages or functionality based on which action (or the notification itself) they clicked.