Skip to content

JavaScript Tutorial Web APIs

The Notifications API

Lesson 214 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

The Notifications API lets a page show a system notification outside the browser window, if the user allows it.

> Permission prompts and notifications need a real, secure page. The Try it sandbox blocks them, so the code below is for your own pages.

Check the permission

script.js
JS
console.log(Notification.permission);
// "default" (not asked yet), "granted" or "denied"

Ask for permission

Ask only after a user action, and only when the user would clearly benefit.

script.js
JS
document.querySelector("#enable").addEventListener("click", async () => {
  if (!("Notification" in window)) {
    console.warn("This browser does not support notifications.");
    return;
  }

  const permission = await Notification.requestPermission();
  if (permission === "granted") {
    new Notification("Notifications on", { body: "We will tell you when your order ships." });
  }
});

Browsers ignore or block permission requests made on page load, with no user action. If a user selects “Block”, you cannot ask again. They must change it in the browser settings.

Showing one

script.js
JS
const notification = new Notification("New message", {
  body: "Maya sent you a message",
  icon: "/images/avatar.png",
  tag: "message-1",           // replaces earlier notifications with the same tag
  data: { url: "/inbox" }
});

notification.addEventListener("click", () => {
  window.focus();
  location.href = notification.data.url;
  notification.close();
});

Common options

OptionPurpose
bodythe text under the title
icona small image
taggroups or replaces notifications
dataany data to use later
silentno sound
requireInteractionstay until dismissed (use sparingly)

Good etiquette

Notifications can be very annoying, and sites that abuse them train users to click “Block” for everyone.

  • Explain the benefit first, in the page, before the browser prompt.
  • Ask when it makes sense (after a user chooses “notify me”), never on load.
  • Send only useful notifications: replies, shipping updates, reminders the user asked for.
  • Let users turn them off in your own settings.
  • Never use them for ads.

Other details

  • On many systems, the page must be open (or have a service worker) for new Notification(). For notifications when the page is closed, you need Push with a Service Worker, which is a larger topic.
  • Mobile browsers have more restrictions, and some require a service worker.
  • Respect the user’s choice. If Notification.permission === "denied", show a quiet message instead of asking again.

An in-page alternative

Often a message on the page is enough and avoids the permission prompt altogether: a status message with role="status", or a small toast.

info
Privacy
Notifications are a permission-based feature. Treat the user’s attention as something to earn, not something to take.