Skip to Content
Course content

94: The Notification API

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time when developers first dive into the Notification API: they assume it works like a standard alert() or a console.log(). They write a single line of code—new Notification("Time is up!")—refresh the page, and... nothing happens. They assume the browser is bugged or their code is broken.

The "Instant Trigger" Myth vs. The Permission Gatekeeper

The misconception is that the Notification API is a direct command to the OS. In reality, it's a request that must be vetted by the user first. Because notifications can be incredibly annoying (we've all dealt with those aggressive "Allow notifications?" popups on every random blog), browsers treat this as a high-privilege action. If you haven't explicitly requested and been granted permission, the browser will simply ignore your new Notification() call without throwing a loud error.

Here is how you actually handle the handshake. You have to check the current permission state and, if it's "default" (meaning the user hasn't decided yet), ask them for access:

async function notifyUser() {
  // Check if the browser even supports notifications
  if (!("Notification" in window)) {
    console.log("This browser does not support desktop notifications.");
    return;
  }

  // If permission is already granted, just fire it off
  if (Notification.permission === "granted") {
    showAlert();
  } 
  // If we haven't asked yet, we need to request it
  else if (Notification.permission !== "denied") {
    const permission = await Notification.requestPermission();
    if (permission === "granted") {
      showAlert();
    }
  }
}

function showAlert() {
  new Notification("Focus Session Complete!", {
    body: "Your 25 minutes are up. Time to stretch!",
    icon: "/assets/timer-icon.png"
  });
}

notifyUser();

Beyond the Basic Text: Controlling the Payload

Once you've cleared the permission hurdle, you'll realize that a plain string as the first argument is pretty boring. I rarely use the basic constructor because it looks like a system error. To make a notification feel like a part of a professional app, you need the options object.

The body property allows you to provide a detailed description, and the icon property is essential for branding. But the real power comes from the event listeners. You can actually make the notification interactive by listening for a click event on the notification instance itself.

Imagine you're building a messaging app. You don't just want to tell the user "You have a message"; you want them to be brought directly to that conversation when they click the alert:

const notification = new Notification("New Message from Sarah", {
  body: "Are we still meeting at 5pm?",
  icon: "/images/sarah-avatar.jpg",
  tag: "message-alert" // Using a tag prevents duplicate notifications from stacking
});

notification.onclick = (event) => {
  event.preventDefault(); // Prevent the browser from focusing the window immediately
  window.focus();
  window.location.href = "/chats/sarah";
  notification.close();
};

One quick tip: Notice that tag property. If you send ten notifications with the same tag, the browser will usually replace the previous one instead of flooding the user's screen with ten separate boxes. It's a small detail, but it's the difference between a helpful tool and "malware-adjacent" behavior.




📋 Practical Task

Build a Pomodoro Timer Notification System

Create a small application that simulates a Pomodoro timer. The app should have a "Start Timer" button that initiates a 5-second countdown (for testing purposes, rather than a full 25 minutes).

Your implementation must include the following:

  • A permission check that requests notification access only when the "Start Timer" button is clicked.
  • A setTimeout or setInterval that triggers a notification exactly when the timer hits zero.
  • The notification must include a body text telling the user to take a break and a tag to ensure multiple timers don't spam the screen.
  • A click event listener on the notification that logs "User acknowledged the break!" to the console and closes the notification.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.