JavaScript Desktop Notification

Objectives of the blog

After reading this blog, you will able to setup the desktop notification for your site. You will also be able to customize your notification by your own message, image, icon etc.

Benefit of Desktop Notification

Suppose you want to notify your customer outside the webpage then we can use the desktop notification as if you have enabled desktop notification for email, you don’t need to check emails regularly. In every email, you got a notification.

Code for Desktop Notification

Add the below function in the script tag in the head of the HTML.

function showNotification() {
    // Verify if the user's browser supports notifications or not
    if (!("Notification" in window)) {
        alert("Your browser does not support the desktop notification");
    // Verify if notification's permissions have already been granted or not
    else if (Notification.permission === "granted") {
        // Create Notification
        var options = {
            body: 'Simple notification message line 1.\nSecond line of notification message.', // body of the notification
            dir: 'ltr', // direction of message ltr: left to right. rtl : right to left.
            image: '', // Add image if required to show
            icon: '', // Add icon if required to show
        var title = "Knowband Blog";
        var notification = new Notification(title, options);
        //Add the notification click link
        notification.onclick = function (event) {
            event.preventDefault(); // prevent the browser from focusing the Notification's tab
  '', '_blank');
            notification.close();//Close the notification after click
    // If no permissions, ask the user for permission
    else if (Notification.permission !== "denied") {
        Notification.requestPermission().then(function (permission) {
            // If the user accepts, let's create a notification
            if (permission === "granted") {
                var notification = new Notification("Hi there!");

You can trigger this function through event as you wish. For testing purpose, you can check this by adding a button. Use below code for button in the body

<button onclick="showNotification()">Show Notification!</button>

Note: If you are running this code on the local system then use the local sever i.e. localhost.

Output Screen

Output Screen

Sunny Saurabh

Sunny Saurabh

Sunny Saurabh is an experienced Software engineer in C# and ASP.NET as well as an expert as a PHP developer. He has also expert in database design, server maintenance and security. He has achieved this goal only in the short span of 3yrs and still looking forward to achieving more in the IT industry. He lives in New Delhi and his hobby to write the technical writeups.

One thought on “JavaScript Desktop Notification

Leave a Reply

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