JavaScript Notes
Learn the JavaScript Web Notification API to send browser push notifications. Covers Notification.requestPermission, options, click/close events, and Service Worker integration with interview Q&A.
The Web Notification API lets web pages send native OS-level notifications to users — the same pop-ups you see from desktop apps. These appear even when the browser is minimised. Combined with Service Workers, they power push notifications for Progressive Web Apps.
💡 Requirements: Notifications require user permission (shown once per origin) and HTTPS (or localhost). You cannot force notifications — the user must explicitly grant access.
Permission Flow
Requesting Permission
async function requestNotificationPermission() {
const permission = await Notification.requestPermission();
console.log("Permission:", permission);
return permission;
}
requestNotificationPermission();"Permission: granted" // if user clicks Allow "Permission: denied" // if user clicks Block "Permission: default" // if user dismisses the prompt
Always checkNotification.permissionfirst — if it's"denied",requestPermissionis not shown again and the user must manually unblock your site in browser settings.
Sending a Basic Notification
"Notification sent!" // OS shows a native notification pop-up: "New Message 📬" // Body: "You have 3 unread messages from Alex." // Click: opens /messages tab "Notification dismissed" // when user closes it
Notification Options Reference
Complete Pattern with Permission Check
async function notify(title, options = {}) {
// 1. Check support
if (!("Notification" in window)) {
console.warn("This browser does not support notifications");
return;
}
// 2. Request if not yet decided
if (Notification.permission === "default") {
await Notification.requestPermission();
}
// 3. Send if granted
if (Notification.permission === "granted") {
return new Notification(title, options);
} else {
console.warn("Notification permission denied");
return null;
}
}
// Usage
notify("Order Shipped! 🚚", {
body: "Your order #4521 is on its way.",
icon: "/icons/truck.png",
tag: "order-4521",
});// Browser shows native notification: "Order Shipped! 🚚" // "Your order #4521 is on its way."
Notifications with Service Workers (Persistent Push)
Service Worker notifications work even when the page is closed.
// When a push message arrives from server: // → OS shows notification even if browser tab is closed // → Click opens the specified URL
Notification API vs Push API
| Notification API | Push API | |
|---|---|---|
| Trigger | Client-side code | Server → Service Worker |
| Works when page closed | ❌ No | ✅ Yes (via SW) |
| Requires subscription | ❌ No | ✅ Yes (VAPID keys) |
| Use case | In-page alerts | Real push notifications |
When to Use Notifications
- Chat apps — new messages while the user is on a different tab
- E-commerce — order status updates (shipped, delivered)
- Calendars — meeting reminders
- Breaking news — alert when a major story is published
- Background tasks — notify when a long export/download finishes
Common Mistakes
- Requesting permission immediately on page load — this is the #1 UX mistake. Show a contextual prompt first ("Want to get order updates?"), then call
requestPermission. - Not checking
Notification.permission === "denied"— if denied, silently fall back; don't show an error. - Sending too many notifications — users will block your site. Reserve notifications for genuinely important events.
- Forgetting HTTPS — the API is unavailable on insecure origins.
- Using Notification API for background push — you need the Push API + Service Worker for that.
- Not handling
onclick— without it, clicking the notification does nothing useful.
Interview Questions
Q1. What are the three possible values of Notification.permission?
"default"(user hasn't decided),"granted"(approved),"denied"(blocked). Once"denied", you cannot callrequestPermissionagain — the user must manually unblock the site.
Q2. How do you send a notification that replaces a previous one?
Use thetagoption. If a notification with the sametagis already visible, the new one replaces it instead of stacking. Userenotify: trueif you want the alert sound to replay.
Q3. What is the difference between the Notification API and the Push API?
The Notification API creates in-browser notifications from client-side code — the page must be open. The Push API (used with Service Workers) receives messages pushed from a server and can display notifications even when the browser tab is closed.
Q4. Why should you not request notification permission immediately on page load?
Users haven't yet seen any value from your app. An immediate prompt is perceived as intrusive and results in higher denial rates. Best practice is to show a contextual in-app prompt first, explaining why notifications are useful, then request permission when the user opts in.
Q5. What does requireInteraction: true do?
It prevents the notification from auto-dismissing (on desktop). The notification stays visible until the user explicitly clicks or closes it. Useful for urgent alerts.
Q6. How do you open a URL when a notification is clicked?
Handle theonclickevent on the Notification object (ornotificationclickin a Service Worker): ``js notification.onclick = () => { window.focus(); window.open("/target-page"); notification.close(); };``
Q7. What is the vibrate option?
It specifies a vibration pattern in milliseconds for mobile devices: alternating on/off durations. For example, [200, 100, 200] = vibrate 200ms, pause 100ms, vibrate 200ms.Key Takeaways
- Notifications require HTTPS and explicit user permission — always check and handle
"denied". - Never request permission immediately on page load — use contextual prompts tied to user actions.
- Use the
tagoption to group or replace related notifications instead of spamming the user. - For push notifications that work when the page is closed, combine the Push API with Service Workers.
- Handle
onclickto provide a meaningful action when users click the notification. requireInteraction: truekeeps urgent notifications visible until the user acts on them.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Notification API in JavaScript — Push Notifications Tutorial.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, notification
Related JavaScript Master Course Topics