DEV Community

Arhan Khan
Arhan Khan

Posted on

Notification API for Beginners: Send Browser Notifications with JavaScript

Web apps can do something most beginners never expect: send a real notification to the user's desktop or phone, even when the tab is in the background. That is the Notification API — a small browser feature behind reminders, chat alerts, and "your download is ready" messages.

Before you can send anything, you must ask the user for permission. The browser shows its own prompt, and the user can allow, block, or ignore it. Your code cannot send a notification until permission is granted — and you should only ask at a moment when the user understands why.

async function askForNotifications() {
  const permission = await Notification.requestPermission();
  if (permission === "granted") {
    new Notification("Notifications enabled", {
      body: "We will let you know when your task is done.",
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

A notification has a title and options: a body message, an icon, a tag to replace an older notification with the same tag, and a flag to keep it visible until the user dismisses it.

new Notification("Timer finished", {
  body: "Your 25-minute focus session is complete.",
  icon: "/icons/timer.png",
  tag: "focus-timer",
  requireInteraction: true,
});
Enter fullscreen mode Exit fullscreen mode

Two rules matter. First, notifications only work on secure pages (HTTPS or localhost) — the browser will refuse them on plain HTTP. Second, never ask for permission the moment the page loads. Users who are interrupted by a permission prompt before they know what your site does will almost always click Block, and browsers remember that choice.

The Notification API pairs naturally with service workers: a service worker can show notifications even when your site is not open, which is how real apps deliver chat messages and reminders. But even on its own, in a single page, it turns a silent web app into one that can tap the user on the shoulder at exactly the right moment.

Top comments (0)