Skip to content

Notifications API

This lesson explains Notifications API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Device Notification API Overview

The HTML5 Notification API allows web applications to display system-level notifications to users. Notifications can appear outside the browser tab and are useful for alerts, reminders, messages, background updates, task status, calendar events, chat apps, email apps, and Progressive Web Apps.

Because notifications can interrupt users, browsers require explicit user permission before a website can show them. Notifications should be used only for useful, timely, and user-requested information.

Feature Description
API Name Notification API
Main Object Notification
Permission Method Notification.requestPermission()
Main Constructor new Notification()
Permission States default, granted, denied
Common Uses Messages, reminders, alerts, PWA updates, background events.

Basic Notification Example

// HTML5 Notification API

if ("Notification" in window) {
  Notification.requestPermission()
    .then((permission) => {
      if (permission === "granted") {
        new Notification(
          "Hello!",
          {
            body: "This is your first browser notification.",
            icon: "/images/notification-icon.png"
          }
        );
      }
    });
} else {
  console.log("Notifications are not supported.");
}

This example checks browser support, requests permission, and shows a notification only after permission is granted.

How Notification API Works

Step Description Example Syntax
Check Support Verify browser supports notifications. "Notification" in window
Request Permission Ask user to allow notifications. Notification.requestPermission()
Check Permission Read current permission state. Notification.permission
Create Notification Show a browser notification. new Notification("Title", options)
Handle Events Respond to click, close, show, or error events. notification.onclick = callback

Notification Permission States

State Meaning Recommended Action
default User has not made a choice yet. Ask only after clear user intent.
granted User allowed notifications. Show useful notifications when needed.
denied User blocked notifications. Do not repeatedly ask. Show settings help if needed.

Request Notification Permission

async function enableNotifications() {
  if (!("Notification" in window)) {
    console.log("Notification API is not supported.");
    return;
  }

  if (Notification.permission === "granted") {
    console.log("Notifications already enabled.");
    return;
  }

  if (Notification.permission === "denied") {
    console.log("Notifications are blocked.");
    return;
  }

  const permission =
    await Notification.requestPermission();

  console.log("Permission:", permission);
}

document
  .querySelector("#enableNotifications")
  .addEventListener("click", enableNotifications);

Request notification permission from a user action, such as clicking an Enable Notifications button. Avoid asking immediately on page load.

Notification Options

const notification =
  new Notification(
    "Order Update",
    {
      body: "Your order has shipped.",
      icon: "/icons/order.png",
      badge: "/icons/badge.png",
      tag: "order-123",
      data: {
        orderId: 123
      },
      requireInteraction: false
    }
  );
Option Description Example
body Main notification message. "New message received."
icon Large notification icon. "/icons/app.png"
badge Small badge icon, usually on mobile. "/icons/badge.png"
tag Groups or replaces similar notifications. "chat-message"
data Custom data stored with notification. { id: 101 }
requireInteraction Keeps notification visible until user interacts, where supported. true
silent Shows notification without sound or vibration, where supported. true

Notification Events

Event When It Fires Common Use
show Notification is displayed. Track notification impression.
click User clicks the notification. Open related page or focus app.
close Notification is closed. Track dismissal.
error Notification fails. Fallback to in-app alert.

Handle Notification Click

const notification =
  new Notification(
    "New Message",
    {
      body: "You received a new chat message.",
      data: {
        url: "/messages/123"
      }
    }
  );

notification.addEventListener(
  "click",
  () => {
    window.focus();

    window.location.href =
      notification.data.url;

    notification.close();
  }
);

This example focuses the current window and navigates to a related page when the user clicks the notification.

Close Notification Automatically

const notification =
  new Notification(
    "Upload Complete",
    {
      body: "Your file was uploaded successfully."
    }
  );

setTimeout(() => {
  notification.close();
}, 5000);

Some notifications can be closed automatically after a short delay, especially when they are informational and not urgent.

Notification from Service Worker

// main.js

navigator.serviceWorker.ready
  .then((registration) => {
    registration.showNotification(
      "Background Update",
      {
        body: "New content is available.",
        icon: "/icons/app.png",
        data: {
          url: "/updates"
        }
      }
    );
  });

Service Workers can show notifications even when the app is not currently focused, making them useful for Progressive Web Apps and background updates.

Handle Service Worker Notification Click

// service-worker.js

self.addEventListener(
  "notificationclick",
  (event) => {
    event.notification.close();

    const url =
      event.notification.data.url || "/";

    event.waitUntil(
      clients.openWindow(url)
    );
  }
);

In Service Workers, notification click handling uses the notificationclick event instead of the normal page-level click event.

Feature Detection

function supportsNotifications() {
  return "Notification" in window;
}

if (supportsNotifications()) {
  console.log("Notification API supported.");
} else {
  console.log("Notification API not supported.");
}

Common Notification API Use Cases

  • Chat message alerts.
  • Email notifications.
  • Calendar reminders.
  • Task completion updates.
  • File upload or download status.
  • Order shipment updates.
  • Offline sync completion.
  • Progressive Web App background updates.

Notification API Best Practices

  • Ask permission only after user intent.
  • Clearly explain why notifications are useful.
  • Do not request permission immediately on page load.
  • Keep notification text short and actionable.
  • Use notification tags to avoid duplicate alerts.
  • Provide in-app notification settings.
  • Respect denied permissions and do not repeatedly ask.
  • Use Service Workers for PWA and background notifications.

Privacy and Accessibility Considerations

  • Do not send sensitive personal information in notification text.
  • Allow users to turn notification categories on or off.
  • Use clear titles and meaningful body text.
  • Avoid excessive or noisy notifications.
  • Make important information available inside the app too.
  • Do not rely only on sound or vibration to communicate meaning.
  • Provide quiet mode or notification preference controls.
  • Respect operating system notification settings.

Common Notification API Mistakes

  • Requesting permission as soon as the page loads.
  • Sending too many notifications.
  • Ignoring denied permission state.
  • Using notifications for non-important updates.
  • Not handling notification click events.
  • Displaying sensitive data in notification text.
  • Not providing in-app notification preferences.
  • Assuming notification behavior is identical across browsers and devices.

Notification API vs Push API

Feature Notification API Push API
Main Purpose Display notifications. Receive server-sent push messages.
Needs Service Worker Not always, but useful for PWAs. Yes.
Works When App Closed Usually needs Service Worker integration. Yes, through Service Worker.
Example Use Show reminder from current page. Server sends new message alert.

Key Takeaways

  • The Notification API displays system-level browser notifications.
  • Use Notification.requestPermission() before showing notifications.
  • Permission can be default, granted, or denied.
  • Use new Notification() for page-level notifications.
  • Use Service Worker notifications for PWA background experiences.
  • Respect privacy, permission choices, accessibility, and user attention.

Pro Tip

Do not ask users for notification permission immediately. First show a friendly in-app explanation such as "Get reminders for important updates", then request permission only after the user clicks an enable button.