DEV Community

Atta
Atta

Posted on • Updated on • Originally published at attacomsian.com

How to show desktop notifications using JavaScript

This post was originally published on attacomsian.com/blog.


JavaScript Notifications API enables web pages to display messages to users on their devices across different platforms. These notifications appear even after the user has switched tabs or moved to another application.

These messages (also called system or desktop notifications) can be used to notify the user about important events such as an email, new social media message, live chat notification, calendar reminders, etc. You can even use system notifications to send marketing campaigns.

In this tutorial, I'll explain the basic usage of Notifications API to display messages to the user while the site is opened in a browser tab.

API Usage

The Notifications API is fairly new and it may not work at older browsers. Therefore, you should explicitly verify if the API is supported by the browser or not before showing a message. You can do this by checking if the window object has a property called Notification:

if(!window.Notification) {
    console.log('Browser does not support notifications.');
} else {
    // display message here
}
Enter fullscreen mode Exit fullscreen mode

On supported platforms, displaying a desktop notification involves two things: requesting permission and creating a new notification to display to the user.

Note: The Notification API requires your website to use an SSL certificate. It does not work on insecure origins (HTTP).

Requesting Permission

The user needs to grant the current origin permission to show desktop notification. You can easily check if the user has already granted permission to display system notifications using Notification.permission property. This property has the following possible values:

  • default - The user has not yet decided to accept notifications from your site
  • granted - The user has allowed your site to display notifications
  • denied - The user has chosen to block notifications from your site

If it is the first case, you can request permission from the user by using requestPermission() method of the Notifications API. It will open a dialog to ask the user to either allow or block notifications from this site. Once the user has made a choice, the setting will be saved for the current session.

If the user has already denied the request for showing notifications, we can not do anything. The browser will ignore any request to show a notification or request permission again.

if (!window.Notification) {
    console.log('Browser does not support notifications.');
} else {
    // check if permission is already granted
    if (Notification.permission === 'granted') {
        // show notification here
    } else {
        // request permission from user
        Notification.requestPermission().then(function(p) {
           if(p === 'granted') {
               // show notification here
           } else {
               console.log('User blocked notifications.');
           }
        }).catch(function(err) {
            console.error(err);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

The requestPermission() method returns a promise. The callback function will be called once the promise is either resolved or rejected (upon user choice of notifications).

Showing Notification

If the user has chosen to accept notifications from our site, you can create a new desktop notification using Notification() constructor to display it to the user. Just pass a title to the constructor to create a new notification.

var notify = new Notification('Hi there!');
Enter fullscreen mode Exit fullscreen mode

Optionally, you can also pass an options object to specify text direction, body text, icon to display, notification sound to play, and more.

var notify = new Notification('Hi there!', {
    body: 'How are you doing?',
    icon: 'https://bit.ly/2DYqRrh',
});
Enter fullscreen mode Exit fullscreen mode

Putting everything all together, we can create a function that will show a desktop notification once called, requesting permission if not already granted:

function notifyMe() {
    if (!window.Notification) {
        console.log('Browser does not support notifications.');
    } else {
        // check if permission is already granted
        if (Notification.permission === 'granted') {
            // show notification here
            var notify = new Notification('Hi there!', {
                body: 'How are you doing?',
                icon: 'https://bit.ly/2DYqRrh',
            });
        } else {
            // request permission from user
            Notification.requestPermission().then(function (p) {
                if (p === 'granted') {
                    // show notification here
                    var notify = new Notification('Hi there!', {
                        body: 'How are you doing?',
                        icon: 'https://bit.ly/2DYqRrh',
                    });
                } else {
                    console.log('User blocked notifications.');
                }
            }).catch(function (err) {
                console.error(err);
            });
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we can call the above function when the user clicks a button:

<button onclick="notifyMe()">Notify Me</button>
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can bind the above function to body onload event which will be called once the web page is completely loaded:

<!DOCTYPE html>
<html>
<body onload="notifyMe()">
<!-- body content-->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

✌️ I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter to get web development tutorials & protips every week.


Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.

Top comments (9)

Collapse
 
anwar_nairi profile image
Anwar

I am very interested in adding native notification to my web app. For the moment I use in app notification, kinda looks olddie for me...

Do you know which strategy I could use server side? How a client can be aware of new notifications?

Collapse
 
attacomsian profile image
Atta

You need to implement web push notifications if you want to send notifications from the server-side. It is a bit complex usage of Notification API.

Last year, I did something like this. Here are the links to source code:

Collapse
 
nenadkaevik profile image
Nenad Kaevik

I will have to add a note here. Notifications work only on https protocol :)

Collapse
 
attacomsian profile image
Atta

Yes, you are right :) I updated the post.

Collapse
 
kienngo profile image
ken

Thanks for the post. Will definitely try this out.

Collapse
 
mativl profile image
Matias Vallarino

Thanks, this´s great

Collapse
 
anfossistudio profile image
AnfossiStudio

Thank you very much <3

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Thanks !

Collapse
 
bbarbour profile image
Brian Barbour

Atta, thanks for sharing this. I bookmarked this article because I have no doubt I'll need to do this in the future.