How to Use the JavaScript Notification API

This guide provides a comprehensive overview of the Web Notification API in JavaScript, explaining how web applications can display native system notifications to users outside the context of a browser tab. You will learn what the API is, how to request user permissions, how to construct and customize notifications, and how to handle user interaction events directly within your code.


What is the Notification API?

The Notification API is a web standard interface that allows web pages and web applications to deliver system-level notifications to users. Unlike in-page modal dialogs or banners, these notifications appear directly within the host operating system’s native notification center (such as Windows Action Center, macOS Notification Center, or mobile notification trays), even when the user is working in a different tab or application.


Understanding Notification Permissions

Before an application can display notifications, the user must explicitly grant permission. The API provides three distinct permission states via Notification.permission:

To prompt the user for access, use the Notification.requestPermission() method, which returns a Promise:

async function askNotificationPermission() {
  if (!("Notification" in window)) {
    console.error("This browser does not support desktop notifications.");
    return false;
  }

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

  if (Notification.permission !== "denied") {
    const permission = await Notification.requestPermission();
    return permission === "granted";
  }

  return false;
}

Creating and Displaying Notifications

Once permission is granted, you can trigger a notification using the Notification constructor. The constructor accepts two arguments: a required title string and an optional configuration object.

function showNotification() {
  if (Notification.permission === "granted") {
    const options = {
      body: "You have received a new update.",
      icon: "/icons/notification-icon.png",
      tag: "app-update",
      renotify: true,
      silent: false
    };

    const notification = new Notification("New Alert", options);
  }
}

Common Configuration Options:


Handling Notification Events

The Notification instance emits several lifecycle events that allow you to execute JavaScript based on user interactions:

function sendInteractiveNotification() {
  const notification = new Notification("Message from Support", {
    body: "Click here to view your open ticket."
  });

  notification.onclick = () => {
    window.focus();
    window.location.href = "https://example.com/tickets/123";
    notification.close();
  };
}

Security and Implementation Requirements