Recipe 13.9

Showing a Notification

Use the Notification API to show native pop-up notifications. Notifications require the user to first grant permission, then you can show a notification by creating a Notification object with some message text.

Notifications can also include arbitrary data, and you can listen for events such as when the notification is clicked or when it is closed, to create actionable notifications.

Demo

Code

JavaScript
const button = document.querySelector('#notification-button');

async function getPermission() {
  if (Notification.permission !== 'denied') {
    await Notification.requestPermission();
  }

  return Notification.permission === 'granted';
}

button.addEventListener('click', async() => {
  if (await getPermission()) {
    new Notification('Hello!', {
      body: 'This is a test notification'
    });
  }
});
HTML
<button id="notification-button" class="btn btn-primary">Show Notification</button>
Web API Cookbook
Joe Attardi