Displaying Notifications with showNotification()
You'll learn how to create visible push notifications with customizable title, body, icon, and other options using the service worker's showNotification() method.
What Is showNotification()?
When your service worker receives a push event, it needs to actually display something to the user. That's where showNotification() comes in. This method creates the visual notification that appears on the user's device, complete with text, images, and interactive elements.
You call showNotification() on the registration object inside your push event handler. It takes two arguments: a title (required) and an options object (optional but highly recommended).
Basic Structure
self.addEventListener('push', (event) => {
const options = {
body: 'You have a new message!',
icon: '/images/icon-192.png',
badge: '/images/badge-72.png'
};
event.waitUntil(
self.registration.showNotification('New Notification', options)
);
});
Key Options You Can Configure
- body: The main message text beneath the title
- icon: A larger image displayed in the notification (usually 192x192 or larger)
- badge: A small monochrome icon for the device's notification tray (typically 72x72)
- image: A full-width banner image for rich notifications
- tag: Groups notifications together—new ones with the same tag replace old ones
- data: Custom data you can access later when the user interacts
- actions: Buttons users can click (e.g., "Reply", "Dismiss")
Think of it like designing a mini poster: the title is your headline, the body is your message, and icons/images are your visuals that grab attention.
Key Takeaway: showNotification() transforms push events into visible, customizable notifications by accepting a title and options object containing body text, images, badges, and interactive elements.