HTML Notification API

📢 Introduction to the Notification API

The Notification API enables web pages to send system-level notifications to users, even when the page is in the background or closed. This is great for alerts, reminders, messages, or updates — keeping users informed in real-time. 🚀

>>“Engage users beyond the browser with timely notifications.” 📲

📌 How Notifications Work

Notifications are displayed by the operating system, triggered by your web page’s JavaScript. Users must grant permission for your site to send notifications.

⚙️ Basic Notification Example

Here’s how to request permission and display a notification:

Simple Notification

if ('Notification' in window) {
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      new Notification('Hello!', {
        body: 'This is a sample notification from your website.',
        icon: 'https://example.com/icon.png'
      });
    } else {
      console.log('Notification permission denied');
    }
  });
} else {
  console.log('This browser does not support notifications.');
}

🧩 Notification Options

OptionDescription
bodyText displayed inside the notification.
iconURL of an icon image shown with the notification.
tagA string ID to replace/stack notifications with the same tag.
renotifyIf true, re-displays a notification with the same tag.
silentIf true, notification is silent (no sound/vibration).

🛠️ Handling Notification Clicks

You can listen for user interactions like clicks on the notification:

Notification Click Event

const notification = new Notification('Hi there!', {
  body: 'Click me to open a website.',
  icon: 'https://example.com/icon.png'
});

notification.onclick = () => {
  window.open('https://example.com', '_blank');
};

🧠 Best Practices

  • Always ask for permission before sending notifications.
  • Use notifications sparingly to avoid annoying users.
  • Provide meaningful, clear messages with useful actions.
  • Consider using Service Workers for background notifications (Push API).

🔗 Useful Resources

>>“Notifications keep users connected — use them wisely and respectfully.” 🔔