Ticker

6/recent/ticker-posts

πŸ”” Notifications API in JavaScript – The “Hey, Look Here!” Feature Done Right

πŸ”” Notifications API in JavaScript – The “Hey, Look Here!” Feature Done Right

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

Reactions

Post a Comment

0 Comments