Notification API Support and Permission Handling

Detect browser Notification API support, handle permission requests, and implement push notifications. Covers service worker integration and best practices.

Platform

Detailed Explanation

Notification API Detection

The Notification API allows web applications to display system-level notifications to the user, even when the page is not focused or is running in the background via Service Workers.

Detection

const hasNotifications = 'Notification' in window;

Permission Flow

async function requestNotificationPermission() {
  if (!('Notification' in window)) {
    return 'unsupported';
  }

  if (Notification.permission === 'granted') {
    return 'granted';
  }

  if (Notification.permission === 'denied') {
    return 'denied';
  }

  // permission is 'default' - ask the user
  const result = await Notification.requestPermission();
  return result;
}

Showing a Notification

function showNotification(title, options = {}) {
  if (Notification.permission !== 'granted') return;

  return new Notification(title, {
    body: options.body || '',
    icon: options.icon || '/icon-192.png',
    badge: options.badge || '/badge-72.png',
    tag: options.tag, // Replace existing with same tag
    silent: options.silent || false,
    requireInteraction: options.requireInteraction || false,
  });
}

Permission States

State Meaning
default User has not been asked yet
granted User allowed notifications
denied User blocked notifications

Best Practices

  1. Ask in context: Request permission after the user performs an action that would benefit from notifications, not on page load
  2. Explain value: Show a custom UI explaining why notifications are useful before triggering the browser prompt
  3. Respect denial: If permission is denied, do not repeatedly ask
  4. Use tags: Prevent notification spam by grouping related notifications with the same tag
  5. Service Worker: Use Service Worker notifications for persistence when the page is closed

Use Case

Powers real-time alerts for messaging apps, email clients, task managers, monitoring dashboards, and e-commerce order updates. Combined with Service Workers, notifications work even when the user is not actively using the web app.

Try It — Browser Feature Detector

Open full tool