User Engagement

Notifications API

Engage users with native system notifications - deliver timely updates, reminders, and messages directly to their desktop or mobile device.

How do you show browser notifications?

Request permission with Notification.requestPermission() after a user action. If it returns "granted", create a notification with new Notification("Title", { body, icon }). To send notifications while the site is closed, use the Push API with a Service Worker. Notifications require HTTPS.

button.addEventListener("click", async () => {
  if (await Notification.requestPermission() === "granted") {
    new Notification("Lesson complete!", { body: "Next: CSS Grid", icon: "/icon.png" });
  }
});

Key Features

Cross-Platform

Works on desktop and mobile devices

Customizable

Rich content with actions and media

Permission-based

User controls notification access

Interactive Notifications Demo

Experience the full power of web notifications with permission handling, rich content, action buttons, and real-world examples.

Notifications API Architecture

Notification Lifecycle

  • Permission: Request user consent
  • Creation: Display notification
  • Interaction: Click, close, action buttons
  • Events: Show, click, close, error
  • Management: Auto-dismiss, persistence

Platform Integration

  • Desktop: Native OS notifications
  • Mobile: Push notification integration
  • Persistent: Service Worker notifications
  • Rich Media: Images, badges, sounds
  • Actions: Interactive buttons

Permission Management & Best Practices

Permission States & Handling

Checking Permission
// Check current permission status console.log('Permission:', Notification.permission); // Possible values: // "default" - User hasn't been asked yet // "granted" - User has granted permission // "denied" - User has denied permission if (Notification.permission === 'granted') { // Can show notifications showNotification(); } else if (Notification.permission === 'default') { // Should request permission requestPermission(); }
Requesting Permission
// Modern promise-based approach async function requestNotificationPermission() { try { const permission = await Notification.requestPermission(); if (permission === 'granted') { console.log('Notification permission granted'); return true; } else { console.log('Notification permission denied'); return false; } } catch (error) { console.error('Error requesting permission:', error); return false; } }

Permission Request Best Practices

  • • Context: Request permission when user expects notifications (e.g., subscribing to updates)
  • • Explanation: Explain why notifications are useful before requesting
  • • Graceful Degradation: Provide alternatives if permission is denied
  • • Timing: Don't request immediately on page load
  • • User Control: Provide settings to manage notification preferences

Creating Rich Notifications

Basic Notification Creation

Simple Notification
// Basic notification const notification = new Notification('Hello!', { body: 'This is a simple notification', icon: '/icon.png', tag: 'simple-notification' }); // Auto-close after 5 seconds setTimeout(() => { notification.close(); }, 5000);
Rich Notification Options
const notification = new Notification('New Message', { body: 'You have received a new message', icon: '/message-icon.png', badge: '/badge.png', image: '/preview.jpg', tag: 'message-123', data: { messageId: 123, sender: 'John' }, requireInteraction: true, silent: false, timestamp: Date.now() });

Advanced Notification Features

Action Buttons
const notification = new Notification('New Email', { body: 'You have 3 unread emails', actions: [ { action: 'reply', title: 'Reply', icon: '/reply-icon.png' }, { action: 'mark-read', title: 'Mark as Read', icon: '/read-icon.png' } ] });
Notification Replacement
// Using 'tag' to replace notifications function showProgress(progress) { new Notification('Download Progress', { body: `${progress}% complete`, tag: 'download-progress', // Same tag replaces previous icon: '/download-icon.png', silent: true }); } // Only one notification visible at a time showProgress(25); showProgress(50); showProgress(75);

Notification Event Handling

Handle user interactions with notifications:

const notification = new Notification('Interactive Notification', { body: 'Click me or use the actions below', actions: [ { action: 'like', title: 'Like' }, { action: 'reply', title: 'Reply' } ], data: { postId: 123 } }); // Handle notification click (main body) notification.onclick = (event) => { console.log('Notification clicked:', event); // Access notification data const data = event.target.data; // Focus the browser window window.focus(); // Navigate to specific page window.location.href = `/post/${data.postId}`; // Close the notification notification.close(); }; // Handle notification shown notification.onshow = (event) => { console.log('Notification shown'); // Track analytics analytics.track('notification_shown', { type: 'post_like', timestamp: Date.now() }); }; // Handle notification closed notification.onclose = (event) => { console.log('Notification closed'); }; // Handle notification error notification.onerror = (event) => { console.error('Notification error:', event); };

Persistent Notifications with Service Workers

Service Worker Notification Setup

Main Thread (Register SW)
// Register service worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(registration => { console.log('SW registered:', registration); // Show persistent notification registration.showNotification('Persistent Notification', { body: 'This notification persists even when tab is closed', icon: '/icon.png', badge: '/badge.png', tag: 'persistent-notification', requireInteraction: true }); }); }
Service Worker (sw.js)
// Handle notification click in service worker self.addEventListener('notificationclick', (event) => { console.log('Notification clicked:', event); // Close the notification event.notification.close(); // Handle different actions if (event.action === 'reply') { // Handle reply action event.waitUntil(handleReply(event.notification.data)); } else { // Default click action - open app event.waitUntil( clients.openWindow('/dashboard') ); } });

Push Notifications Integration

Combine with Push API for server-triggered notifications:

// Service Worker: Handle push events self.addEventListener('push', (event) => { const options = { body: event.data ? event.data.text() : 'No payload', icon: '/icon.png', badge: '/badge.png', vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: '1' }, actions: [ { action: 'explore', title: 'Explore', icon: '/images/checkmark.png' }, { action: 'close', title: 'Close', icon: '/images/xmark.png' } ] }; event.waitUntil( self.registration.showNotification('Push Notification', options) ); }); // Handle notification interactions self.addEventListener('notificationclick', (event) => { event.notification.close(); if (event.action === 'explore') { // Open specific page event.waitUntil( clients.openWindow('/explore') ); } else if (event.action === 'close') { // Just close, no action needed return; } else { // Default action (click on notification body) event.waitUntil( clients.openWindow('/') ); } });

Use Cases, Patterns & Best Practices

Effective Use Cases

  • • Communication: New messages, mentions, comments
  • • Updates: Breaking news, system status, alerts
  • • Tasks: Reminders, deadlines, appointments
  • • Activity: Likes, shares, follows, achievements
  • • E-commerce: Order updates, price drops, stock alerts
  • • Content: New articles, videos, podcasts

Notification Design Principles

  • • Relevant: Send only valuable, actionable content
  • • Timely: Send at appropriate times for users
  • • Personal: Customize content for individual users
  • • Clear: Use concise, understandable language
  • • Actionable: Include clear next steps

Technical Best Practices

  • • Use meaningful tags to prevent notification spam
  • • Implement proper error handling for denied permissions
  • • Optimize images and icons for notifications
  • • Test across different devices and platforms
  • • Implement notification analytics and tracking
  • • Provide easy unsubscribe mechanisms

User Experience Guidelines

  • • Respect user notification preferences
  • • Provide granular notification controls
  • • Don't send notifications too frequently
  • • Use progressive disclosure for complex notifications
  • • Consider time zones and user schedules
  • • Always provide value with each notification

Advanced Notification Management

Comprehensive notification management system:

class NotificationManager { constructor() { this.activeNotifications = new Map(); this.settings = this.loadSettings(); } async requestPermission() { if (!('Notification' in window)) { throw new Error('This browser does not support notifications'); } if (Notification.permission === 'granted') { return true; } const permission = await Notification.requestPermission(); return permission === 'granted'; } async show(options) { if (!await this.requestPermission()) { console.warn('Notification permission denied'); return null; } // Check if this type of notification is enabled if (!this.settings.enabled[options.category]) { return null; } // Replace existing notification with same tag if (options.tag && this.activeNotifications.has(options.tag)) { this.activeNotifications.get(options.tag).close(); } const notification = new Notification(options.title, { body: options.body, icon: options.icon || '/default-icon.png', tag: options.tag, data: options.data, requireInteraction: options.requireInteraction, actions: options.actions || [] }); // Track active notifications if (options.tag) { this.activeNotifications.set(options.tag, notification); } // Set up event handlers notification.onclick = (event) => { this.handleClick(event, options); }; notification.onclose = () => { if (options.tag) { this.activeNotifications.delete(options.tag); } }; // Auto-close after specified time if (options.autoClose) { setTimeout(() => { notification.close(); }, options.autoClose); } return notification; } handleClick(event, options) { event.notification.close(); // Focus browser window if (window.focus) window.focus(); // Execute custom click handler if (options.onClick) { options.onClick(event); } } clearAll() { this.activeNotifications.forEach(notification => { notification.close(); }); this.activeNotifications.clear(); } updateSettings(newSettings) { this.settings = { ...this.settings, ...newSettings }; this.saveSettings(); } loadSettings() { const saved = localStorage.getItem('notification-settings'); return saved ? JSON.parse(saved) : { enabled: { messages: true, updates: true, reminders: true, promotions: false }, quietHours: { enabled: false, start: '22:00', end: '08:00' } }; } saveSettings() { localStorage.setItem('notification-settings', JSON.stringify(this.settings)); } } // Usage example const notificationManager = new NotificationManager(); // Show different types of notifications notificationManager.show({ title: 'New Message', body: 'You have a new message from John', category: 'messages', tag: 'message-123', icon: '/message-icon.png', autoClose: 5000, onClick: () => window.location.href = '/messages/123' });

Code Editor

<button id="ask">Notify me</button>
<p id="status"></p>

Preview

Web Notifications API — step by step

1 / 4
1

Request notification permission

Call Notification.requestPermission() to prompt the user for permission. It returns a Promise resolving to 'granted', 'denied', or 'default'. Always request permission in response to a user action like a button click, not on page load.

1 of 4
⚠️Never Request Permissions on Page Load
Browsers now automatically deny or ignore permission requests that are not triggered by a user gesture (click, keypress, etc.). Requesting notifications immediately on page load feels intrusive and has a very low acceptance rate. Always explain the value of notifications before requesting permission.

🎯 Quick Check

What value does Notification.requestPermission() resolve to when the user grants permission?

Web Notifications API: summary

Key points

  • Asking for permission on page load gets you blocked; ask when the value is clear to the user.
  • If the user denies permission, you can't ask again from code; they must change it in browser settings.
  • iOS supports web push only for PWAs added to the home screen.

Frequently asked questions

›Why are my notifications not showing?

Check that permission is "granted", that the page is on HTTPS, and that the operating system's Do Not Disturb or the browser's notification settings aren't blocking them.