Lesson 13 / 29
Push notifications
Implement push notifications to engage users with timely messages.
Push notification flow
Push notifications require permission from users. Your server sends messages to a push service, which delivers them to the service worker. Users see notifications even when your app is closed.
Request push permission and show notification
Request permission and handle push events in the service worker.
// Request permission
Notification.requestPermission().then(permission => {
console.log('Permission granted:', permission);
});
// Handle push in service worker
self.addEventListener('push', event => {
const options = {
body: event.data.text(),
icon: '/icon-192.png',
badge: '/badge-72.png'
};
event.waitUntil(
self.registration.showNotification('My App', options)
);
});
Output:
Users receive push notifications from the service worker.
A common trap
Always request push permission contextually. Asking immediately on page load leads to high rejection rates.
Building engagement through notifications
Best practices for notification timing, content, and frequency.