SHARE
Facebook X Pinterest WhatsApp

Creating Your Own Notifications with the HTML5 Notifications API

Written By
thumbnail
Diogo Souza
Diogo Souza
May 13, 2019

Many people have asked if there is any way to alert users to the website, so I decided to write this article about the HTML5 Notifications API.

HTML5 Notifications API

The Notifications API allows you to view user notifications for events such as new emails, tweets or calendar events, and also user interactions, regardless of which tab is open.

It is important to note that this functionality is not a cross-browser at all. That is, it does not work in all browsers — only those that are webkit users, such as Google Chrome (Firefox has also added this functionality).

But after all, what exactly is this kind of notification? It’s simple, anyone who uses GTalk in one of these browsers that I mentioned above, should have seen that whenever someone sends a message through the chat and you are not with the Gmail tab active, you receive a notification on the screen saying there was an interaction in chat, this is HTML5 Notifications API.

Checking Browser Compatibility

As we’ve seen, not all browsers support the use of the Notification API. For this, we use a code to verify this compatibility.

Listing 1: Checking Compatibility

// Verifying technology support
if (window.webkitNotifications) {
  console.log('Your browser supports Notifications');
} else {
  console.log('Your browser doesn't support Notifications =(');
}

Notification Structure

A notification is made up of a title, a body of text and a representative image (usually where the logo of the site is placed). When you create it, you must specify these attributes so that it is viewed correctly.

To implement the notifications, it is necessary for the user to accept its use, this action must be done by the user himself. In Listing 2 we will see how to request this authorization.

Basically, this authorization should contain a button the user will click to obtain authorization of the notifications.

Listing 2: Requesting User Authorization – HTML

<input type="button" id="click-me" />

Listing 3: JavaScript Code

var Notifications = {
    requestPermission: function(callback) {
        window.webkitNotifications.requestPermission(callback);
    }
};
  
$(function() {
    $('#click-me').click(function() {
        Notifications.requestPermission(function() {
            alert('Permissão concedida');
        })
    });
});

This way, when the user clicks the button, the notification authorization action will be performed.

Now we have almost everything ready, it is only missing to send the notification to the user. But first, we always have to check if the permission was given by the user, in Listing 4 we see how to send this notification to the user.

Listing 4: Sending Notification to User

var Notifications = {
    requestPermission: function(callback) {
        window.webkitNotifications.requestPermission(callback);
    },
      
    showNotification: function(){
        // Checking if the permission was given
         if (window.webkitNotifications.checkPermission() > 0) {
                // In not, asks again for permission
                Notifications.requestPermission(function() {
                    Notifications.showNotification();
                });
         }
         else {
                // Otherwise, creates the notification and sends it
                var notification = window.webkitNotifications.createNotification("http://userserve-ak.last.fm/serve/64s/318711.jpg", "Hello!", "This is the message");
                notification.show();
         }
    }
};

As we can see, the code is very simple to use and very useful in projects. Now, we will see a lib of notifications, that is, a file already prepared with the notification, with only the user calling this notification.

Call the notification like this:

Listing 5: Calling a Notification in a Lib

Notifications.show("http://userserve-ak.last.fm/serve/64s/318711.jpg", "Here, we'll put the notification message");

Now we’ll look at the lib code.

Listing 6: Notification Lib

var Notifications = {
    apiAvailable: function() {
        if(window.webkitNotifications) {
            return true;
        } else {
            return false;
        }
    },
  
    isAuthorized: function() {
        if (!this.apiAvailable()) return false;
  
        return window.webkitNotifications.checkPermission() > 0 ? false : true;
    },
  
    authorize: function(callback) {
        var self = this;
        if (!this.apiAvailable()) return false;
  
        window.webkitNotifications.requestPermission(function() {
            if (self.isAuthorized()) {
                callback();
            }
        });
    },
  
    show: function(url, title, body) {
        if (!this.apiAvailable()) return false;
  
        var self = this;
  
        if (this.isAuthorized()) {
            var popup = window.webkitNotifications.createNotification(url, title, body);
            popup.show();
            setTimeout(function(){
                popup.cancel();
            }, 5000);
        } else {
            this.authorize(function() { 
                //console.log(arguments); 
                self.show(url, title, body); 
            });
        }
    },
      
    checkForPermission: function() {
        if (!this.isAuthorized()) this.callForPermission();
    },
      
    callForPermission: function() {
          
        var authorizeBox = jQuery('
').addClass('notifications-authorize')
                                            .html('

Your browser doesn’t support notifications. <input type=”button” value=”Activate Notifications” />

')
                                          
        jQuery('body').append(authorizeBox);
          
        jQuery('div.notifications-authorize input').click(function(){
            jQuery(this).remove(); 
            Notifications.authorize();
        });
    }
};
  
$(function() {
    Notifications.checkForPermission();
});

Conclusion

In this article, we have seen how to create notifications for users using the Notifications API. I hope you enjoyed, until next time.

About the Author

Diogo Souza works as a Java Developer at PagSeguro and has worked for companies such as Indra Company, Atlantic Institute and Ebix LA. He is also an Android trainer, speaker at events on Java and mobile world.

Recommended for you...

Best VR Game Development Platforms
Enrique Corrales
Jul 21, 2022
Best Online Courses to Learn HTML
Ronnie Payne
Jul 7, 2022
Working with HTML Images
Octavia Anghel
Jun 30, 2022
Web 3.0 and the Future Of Web Development
Rob Gravelle
Jun 23, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.