Use the JavaScript Notification API to Display Native Popups

John Au-Yeung - Jan 23 '21 - - Dev Community

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

The Notifications API lets us display popups that show up as a native desktop or mobile notification. The functionality varies across platforms but they generally provide a way to asynchronously provide information to the user.

Create a New Notification

We can create a new notification with the Notification constructor. It takes 2 arguments. The first is the title, and the second is an object with a variety of properties and is optional:

  • dir: the direction of the displayed notification. Default value is auto, but it can also be rtl for right to left or ltr for left to right.
  • lang: string value for the language. Possible values are BCP 47 language tags.
  • badge: string which contains the URL for an image used to represent the notification when there isn’t enough space to display it.
  • body: a string with the text of the notification.
  • tag: a string with the identifying tag of the notification
  • icon: URL string with the icon’s URL
  • image: URL string for the image to be displayed.
  • data: data we want to be associated with the notification.
  • vibrate: vibration pattern for devices that vibrate.
  • renotify: boolean value specifying whether the user should be notified after a new notification replaces the old one. Default value is false.
  • requireInteraction: indicates whether the notification should remain active until the user clicks or dismisses it. Default value is false.
  • actions: an array of NotificationAction which have actions that are available to the user when the notification is displayed. It’s an object with a name, title, and icon properties.

We can define a simple notification as follows:

const options = {  
  body: "body",  
  icon:  
    "https://www.iconninja.com/files/926/373/306/link-chain-url-web-permalink-web-address-icon.png"  
};const n = new Notification("title", options);
Enter fullscreen mode Exit fullscreen mode

To see the notification, we have to set Notification to always display in our browser.

We should see the text we set and the icon we specified in the icon property.

Methods of the Notification Object

Requesting Permission

We can request permission with the requestPermission static method. It returns a promise which resolves when the permission for showing the notification is allowed or denied.

It resolves with an object which has the permission data.

The browser will ask for permission to display notifications for the domain when we run this method.

For example, we can use it as follows:

(async () => {  
  try {  
    const permission = await Notification.requestPermission();  
    console.log(permission);  
    const options = {  
      body: "body",  
      icon:  
        "https://www.iconninja.com/files/926/373/306/link-chain-url-web-permalink-web-address-icon.png"  
    };  
    const n = new Notification("title", options);  
  } catch (error) {  
    console.log(error);  
  }  
})();
Enter fullscreen mode Exit fullscreen mode

If permission is granted, the console.log in the try block will log granted. Otherwise, it will log denied from the console.log in the catch block.

Closing the Notification Programmatically

We can close a notification programmatically with the close method, which is an instance method of a Notification object.

For example, we can use it as follows:

(async () => {  
  try {  
    const permission = await Notification.requestPermission();  
    console.log(permission);  
    const options = {  
      body: "body",  
      icon:  
        "https://www.iconninja.com/files/926/373/306/link-chain-url-web-permalink-web-address-icon.png"  
    };  
    const n = new Notification("title", options);  
    await new Promise(resolve => {  
      setTimeout(() => {  
        n.close();  
        resolve();  
      }, 5000);  
    });  
  } catch (error) {  
    console.log(error);  
  }  
})();
Enter fullscreen mode Exit fullscreen mode

In the example above, we called close inside the callback of the setTimeout method. This makes it close automatically after 5 seconds.

Event Handlers

Notification objects also have their own event handlers. They events are onclick, onclose, onerror, and onshow. We can assign our own event handler functions to them.

onclick

We can assign an event handler to the onclick property when we want to do something when the notification is clicked. For example, we can write:

(async () => {  
  try {  
    const permission = await Notification.requestPermission();  
    console.log(permission);  
    const options = {  
      body: "body",  
      icon:  
        "https://www.iconninja.com/files/926/373/306/link-chain-url-web-permalink-web-address-icon.png"  
    };  
    const n = new Notification("title", options);  
    n.onclick = () => {  
      alert("Notification clicked");  
    };  
  } catch (error) {  
    console.log(error);  
  }  
})();
Enter fullscreen mode Exit fullscreen mode

This shows an alert in the browser tab when our notification is clicked. The event handler function can take one parameter, which is the event object.

The default behavior is to move focus to the viewport of the notification’s related browsing context. We can call preventDefault() on the event parameter that we pass in to prevent that as follows:

(async () => {  
  try {  
    const permission = await Notification.requestPermission();  
    console.log(permission);  
    const options = {  
      body: "body",  
      icon:  
        "https://www.iconninja.com/files/926/373/306/link-chain-url-web-permalink-web-address-icon.png"  
    };  
    const n = new Notification("title", options);  
    n.onclick = event => {  
      event.preventDefault();  
      alert("Notification clicked");  
    };  
  } catch (error) {  
    console.log(error);  
  }  
})();
Enter fullscreen mode Exit fullscreen mode

We can make the notification do something when it’s closed by assigning an event handler function to the onclose property.

Likewise, we can do the same for the onerror property to handle errors and the onshow property to handle the show event, which is fired when the notification is displayed.

Conclusion

As we can see, the Notification API is a really simple way to display native notifications from the web apps we write. We ask for permission to display notifications with the static Notification.requestPermission method.

Once the promise is resolved when the user allows notifications to be displayed, then we just create a Notification object with the options we want. Then the notification will be displayed.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .