How to Show Notification using Notification API in Javascript

In this tutorial, you will learn how to show notification using Notification API in javascript.  This a great feature if you just want to greet your website users with a nice greeting message in notification or promote some product by providing a discount coupon in notification message.

Any user who visits your website for the first time, he will be asked to grant permission to show him a notification.  User can accept or decline.  It will only happen once so next time when he will visit your website you can show him notification right away.

We are going to cover pure basics of Notification API.  The real power comes when you can send such Notifications also known as web push notifications through your own server or third party service.  Such thing is out of scope of this tutorial. You can google to learn more about web push notifications.

Please replace icon.png with your own icon in javascript code. HTML and Javascript code is given below.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div style="margin-top: 20px; text-align: center;">
        <button style="padding: 10px 5px">Show Notification</button>
    </div>
    
    <script src="script.js"></script>
</body>
</html>

 

Javascript

let button = document.querySelector('button');

button.addEventListener('click', () => {

    if(!window.Notification) return;
   
    Notification
    .requestPermission()
    .then(showNotification)
});


function showNotification(permission){
    if(permission !== 'granted') return;

    let notification = new Notification('My Title', {
        body:"Hi, how are you today?",
        icon:'icon.png'        
    })

    notification.onclick = () => {
        // window.open('https://google.com')

        window.location.href= "https://www.google.com"
    }
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •