πŸ”” Notification API in JavaScript – Complete Tutorial

The Notification API allows web applications to display system-level notifications to users, even when the webpage is not currently in focus (subject to browser support, user permission, and other platform requirements).

πŸ“Œ What is the Notification API?

The Notification API is a browser API used to send desktop or mobile notifications from web applications. Notifications can display a title, body, icon, image, badge, vibration pattern (where supported), and other options.

>>"Notifications help keep users informed about important events even when they're not actively viewing your webpage."

πŸ’‘ Why Use the Notification API?

  • πŸ’¬ Chat message alerts
  • πŸ“§ Email notifications
  • πŸ“… Calendar reminders
  • πŸ›’ Order and delivery updates
  • πŸ“’ Important application alerts

πŸ›  Checking Browser Support

Check Support

if ("Notification" in window) {
  console.log("Notifications supported");
} else {
  console.log("Notifications not supported");
}

πŸ” Requesting Permission

Before showing notifications, the user must grant permission.

Request Permission

Notification.requestPermission()
  .then((permission) => {
    console.log(permission);
  });

πŸ“Š Permission States

StateDescription
"granted"User allowed notifications.
"denied"User blocked notifications.
"default"User has not made a choice yet.

πŸ”” Creating a Notification

After permission is granted, create a notification using theNotification constructor.

Basic Notification

new Notification("Hello!", {
  body: "Welcome to our website."
});

πŸ–Ό Adding an Icon

Notification with Icon

new Notification("Download Complete", {
  body: "Your file is ready.",
  icon: "images/icon.png"
});

βš™οΈ Notification Options

OptionDescription
bodyNotification message.
iconNotification icon.
imageLarge image (where supported).
badgeSmall badge icon (where supported).
tagIdentifier used to replace similar notifications.
langLanguage of the notification.
dirText direction ("ltr", "rtl", or "auto").
requireInteractionKeeps the notification visible until dismissed (browser dependent).
silentSuppresses notification sounds (where supported).
vibrateVibration pattern on supported devices.

πŸ“’ Notification Events

EventDescription
showNotification becomes visible.
clickUser clicks the notification.
closeNotification is closed.
errorAn error occurred while displaying it.

πŸ–± Handling Click Events

Notification Click

const notification =
  new Notification("New Message", {
    body: "Click to open."
  });

notification.onclick = () => {
  window.focus();

  console.log("Notification clicked");
};

❌ Closing a Notification

Close Notification

const notification =
  new Notification("Reminder");

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

πŸš€ Complete Example

Notification Example

if ("Notification" in window) {

  Notification.requestPermission()
    .then((permission) => {

      if (permission === "granted") {

        const notification =
          new Notification(
            "Welcome!",
            {
              body: "Thanks for visiting.",
              icon: "images/logo.png"
            }
          );

        notification.onclick = () => {
          window.focus();
        };

      }

    });

}

πŸ“Š Notification API vs Alert()

FeatureNotification APIalert()
Requires Permissionβœ… Yes❌ No
Blocks JavaScript❌ Noβœ… Yes
Works Outside Page Focusβœ… Often, depending on platform and browser❌ No
Supports Iconsβœ… Yes❌ No
User Friendlyβœ… Yes⚠️ Limited

⚠️ Important Notes

  • πŸ”’ Notifications require user permission.
  • 🌐 Most browsers require a secure context (HTTPS).
  • πŸ–±οΈ Permission requests should generally be triggered by a user action (such as clicking a button).
  • πŸ“± Supported features can vary between browsers and operating systems.

Note

Notifications shown while a website is closed or in the background typically use the Service Worker and Push API, not just the basic Notification constructor shown here.

βœ… Best Practices

  • 🎯 Request permission only when notifications provide clear value.
  • πŸ“’ Avoid sending excessive or unnecessary notifications.
  • πŸ–ΌοΈ Use meaningful titles, icons, and concise messages.
  • πŸ–±οΈ Handle notification click events to guide users to relevant content.
  • πŸ”„ Respect the user's notification preferences and permission choices.

🎯 Summary

The Notification API enables web applications to display system-level notifications after the user grants permission. It supports customizable notification content, icons, and interaction events, making it useful for messaging, reminders, alerts, and application updates. For background notifications when a web app isn't open, it is commonly used together with Service Workers and the Push API.