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

  function displayNotification() {
    if (Notification.permission !== 'granted')
    else {
      var notification = new Notification('Sample Notification', {
        icon: '',
        body: `Todays Date is ${new Date().toLocaleDateString()}`,
      notification.onclick = function () {
        alert("Notification Clicked!!");

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 *


Select Categories