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.


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

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



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

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

    if(!window.Notification) return;

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

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

    notification.onclick = () => {

        window.location.href= ""