Desktop notifications using JavaScript

Desktop notifications using JavaScript

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.

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
}

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

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);
        });
    }
}

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!');

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',
});

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);
            });
        }
    }
}

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

<button onclick="notifyMe()">Notify Me</button>

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>

Conclusion

That's all folks for displaying desktop notifications using JavaScript Notifications API. This is the simplest way to show the notifications which require the site must be opened in the browser. In the future, I'll discuss more advanced usage of Notifications API to send web push notificationsfrom the server side.

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.