Using Notification API In JavaScript

Here, we will learn about how to use Notification API to display a desktop notification in the user’s browser.

What is Notification API?

The interface Notification of Notification API is used to display and configure desktop notification in the user’s browser. It is used to provide some information to users and generally, it works asynchronously

Code to be used for enabling desktop notification.

<!DOCTYPE html>
<html>
<head>
  <title>Desktop Notifications</title>
  <style type="text/css">
    .btnShowNotification{
      padding: 10px;
      background: orange;
      border: navajowhite;
      border-radius: 4px;
      color: #fff;
    }
  </style>
</head>
<body>
  <button class="btnShowNotification" onclick="displayNotification();">Click to Show Notification</button>
</body>
</html>
<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', function () {
    if (!Notification) {
      alert("You can't use Desktop Notifications in this Browser.");
      return;
    }
  });


  function displayNotification() {
    if (Notification.permission !== 'granted')
      Notification.requestPermission();
    else {
      var notification = new Notification('Sample Notification', {
        icon: 'https://www.thecodehubs.com/wp-content/uploads/2019/07/header_logo.png',
        body: `Todays Date is ${new Date().toLocaleDateString()}`,
      });
      notification.onclick = function () {
        alert("Notification Clicked!!");
      };
    }
  }
</script>

We should allow the browser for displaying a notification in order to get the notification from the browser. It will check every time if Notification is granted or not. If it is not granted then it will again request for permission.

There are also various options for the Notification. You can refer them to the official website from here

Code in action:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories