Lesson 14 / 30

Push notifications

Ask permission in context and show push notifications from the service worker, even when the app is closed.

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.