Course contentsShow
← JavaScript
Lesson 1477 of 2,72332. JavaScript in the BrowserFree lesson

Notifications API

Showing system notifications with the Notification constructor after requesting permission.

Notifications API

What you'll learn: How to display system-level notifications to users by requesting permission and using the Notification constructor.

The Core Idea

The Notifications API lets your web application display native system notifications—those pop-up messages that appear outside the browser window, even when the user is in a different application. This is powerful for alerting users about important events, messages, or updates.

Before you can show notifications, you must first request permission from the user. Once granted, you can create notifications using the Notification constructor.

Requesting Permission

You request permission using Notification.requestPermission(), which returns a promise:

Notification.requestPermission().then(permission => {
  if (permission === 'granted') {
    console.log('Permission granted!');
  } else {
    console.log('Permission denied');
  }
});

The user will see a browser prompt asking whether to allow notifications. The result is 'granted', 'denied', or 'default' (not yet decided).

Creating a Notification

Once permission is granted, instantiate a Notification:

Notification.requestPermission().then(permission => {
  if (permission === 'granted') {
    new Notification('Hello!', {
      body: 'This is your first notification.',
      icon: 'icon.png'
    });
  }
});

The first argument is the notification title. The second (optional) is an options object where you can specify the body text, icon, and other properties.

Think of It Like This

Imagine asking someone, "May I send you text messages?" (permission request). If they say yes, you can then send them messages anytime (create notifications). Without permission, your messages won't go through.

Key Takeaway: The Notifications API requires user permission via Notification.requestPermission() before you can display system notifications with new Notification(title, options).