You’ve seen it everywhere:
- “You’ve got a new message”
- “Your order is out for delivery”
- “Reminder: Meeting in 10 mins”
Those little pop-ups outside the browser tab?
π That’s the Notifications API.
Sounds simple… but if you use it wrong, it becomes annoying real fast (and users will block you instantly π ).
Let’s look at how it actually works in real apps.
⚡ What This API Actually Does
The Notifications API lets your app show system-level notifications.
Not alerts. Not modals.
π Actual OS-level notifications (even when the tab isn’t focused)
But there’s a catch:
π User permission is mandatory
No permission → no notifications. Simple.
π Basic Permission Flow
if ("Notification" in window) {
Notification.requestPermission().then(permission => {
console.log(permission);
});
}
Possible values:
- "granted"
- "denied"
- "default"
π Showing a Notification
if (Notification.permission === "granted") {
new Notification("Hello π", {
body: "This is a test notification",
});
}
That’s the simplest version.
π₯ Real Use Case: Trigger on Event
function notifyUser(message) {
if (Notification.permission === "granted") {
new Notification("New Message", {
body: message,
});
}
}
You’d call this when:
- a chat message arrives
- an important event happens
- something needs attention
π‘ Real Developer Insight
Here’s the reality most docs won’t tell you:
π Users hate random notifications.
If you ask for permission immediately on page load…
π instant “Block”
Better approach:
- Wait until user performs an action
- Show context first (“Enable notifications for updates?”)
- Then request permission
Timing matters more than code here.
⚠️ Important: Background Notifications
If you want notifications when the app is closed…
π You need Service Workers + Push API
Basic Notifications API alone:
- Works only when page is open
- Doesn’t run in background
This is where most devs get confused.
⚠️ Common Developer Mistakes
1️⃣ Asking permission on page load
Users don’t even trust your app yet.
2️⃣ Spamming notifications
Leads to blocks → feature becomes useless.
3️⃣ Not checking permission
new Notification("Hello"); // ❌ risky
4️⃣ Expecting it to work offline or in background
Needs Service Worker setup for that.
π Best Practice Summary
✅ Ask for notification permission only after user interaction
✅ Always check Notification.permission before sending
✅ Use notifications only for important, high-value events
✅ Combine with Service Workers for background notifications
✅ Respect user choice and avoid spamming
0 Comments