# Notifications API

The Notifications API allows web pages to control the display of system notifications to the end user. These are outside the top-level browsing context viewport, so they can be displayed even when the user has switched tabs or moved to a different app.

## 1. Requesting Permission

Before you can show a notification, the user must grant permission. This is a security feature to prevent spam.

```javascript
function askNotificationPermission() {
  // Check if the browser supports notifications
  if (!("Notification" in window)) {
    console.log("This browser does not support desktop notification");
    return;
  }

  // Request permission
  Notification.requestPermission().then((permission) => {
    // permission can be 'granted', 'denied', or 'default'
    if (permission === "granted") {
      console.log("Permission granted!");
    }
  });
}
```

## 2. Creating a Notification

Once permission is granted, you can create a notification using the `Notification` constructor.

```javascript
function showNotification() {
  if (Notification.permission === "granted") {
    const notification = new Notification("Hello World!", {
      body: "This is a JavaScript notification.",
      icon: "/path/to/icon.png"
    });
  }
}
```

## 3. Notification Options

The second argument to the constructor is an options object.

*   `body`: The text string of the notification.
*   `icon`: The URL of an image to be used as an icon.
*   `image`: The URL of an image to be displayed in the notification.
*   `tag`: An ID for a given notification that allows you to retrieve, replace, or remove it if necessary.
*   `vibrate`: A vibration pattern for devices with vibration hardware.

## 4. Handling Events

Notifications have events that you can listen to.

*   `click`: Fired when the user clicks on the notification.
*   `close`: Fired when the notification is closed.

```javascript
const notification = new Notification("Click me!");

notification.onclick = (event) => {
  event.preventDefault(); // Prevent the browser from focusing the Notification's tab
  window.open('http://www.mozilla.org', '_blank');
};
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/service-workers-and-pwa]]