SW Notifications

Service Workers: Notifications

registration.showNotification(title, { body, icon, tag, data }) shows a notification whose clicks reach the worker. Web Push wakes the worker with no tab open: the page calls pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }) with your VAPID public key and stores the subscription on your server, which sends messages with a library such as web-push (webpush.sendNotification(subscription, payload)). Both are Baseline Widely available; on iOS 16.4+ push works only in Home Screen web apps.

sw.js: showing pushed messages and handling clicksJavaScript
self.addEventListener('push', (e) => {
  const msg = e.data?.json() ?? { title: 'New update' };
  e.waitUntil(self.registration.showNotification(msg.title, { body: msg.body, data: msg }));
});
self.addEventListener('notificationclick', (e) => {
  e.notification.close();
  e.waitUntil(self.clients.openWindow(e.notification.data.url ?? '/'));
});

Call Notification.requestPermission() only from a user action, such as a click on a "Notify me" button, and never on page load.