Click here to Skip to main content
15,885,953 members
Articles / Web Development / HTML5

HTML5 Web Notifications

Rate me:
Please Sign up or sign in to vote.
4.20/5 (3 votes)
29 Jul 2011CPOL3 min read 40.8K   7   4
Implement notifications like "Mail message arrived", "Printer out of paper" in web applications using the Web Notifications API

Introduction

HTML5 Web NotificationsEver wanted to notify your site clients/users while they are surfing in your site? Notifications like “Mail message arrived”, “Printer out of paper” are available through smart clients for decades but in web applications, they are not so easy to implement. In the past, you could have implemented a blinking behavior that will make the icon of the browser blink or you could add a popup which will annoy your users. There are ways to implement this behavior in a browser specific way (for example Overlay Icon API in IE9) but in HTML5, there is a new option – Web Notifications API. This API isn’t a recommendation yet so things might change in the future and using it is at your own risk.

What is Web Notifications API?

The Web Notifications API is a mechanism for building simple notifications that will alert users outside of the web page. These notifications can be used passively (notify about new tweets, calendar events and more) or actively (with user interactions) and they are not bound to the tab that has focus. The API relay on a permission that is granted by the user. Without indication that notifications were requested by the user, the notifications mechanism won’t work.

Granting Permissions

The first step in using Web Notifications is to check with the user whether he wants to be notified. The following code sample shows how to use the requestPermission and checkPermission functions that are part of the notifications API:

PHP
$('#btnGrantPermission').click(function () {
    if (window.Notifications.checkPermission() == 0) {
        createNotification();
    } else {
        window.Notifications.requestPermission();
    }
});

In the sample, I use jQuery to bind a click event to a button that will check whether we have permission to use notifications. If there is a permission, then the checkPermission function will return 0 and in the sample, I call the createNotification function. If we don’t have permissions, then we use the requestPermission function to request a permission to use notifications in the web page.

Pay attention that the requestPermission must run under an event handler that is triggered by a user!

How to Use Web Notifications API?

In order to use the web notifications API, you need to create a notification. Here is a sample of creating a notification using the createNotification function:

JavaScript
function createNotification() {
    var notification = window.Notifications.createNotification
                       ("1.png", 
                       "New HTML5 Notification Received - Subject", 
                       "More Content...");
    notification.onshow = function () {
        setTimeout(notification.cancel(), 1500);
    }
    notification.show();
}

In the sample, I use the createNotification factory function to create a notification. The function gets a Uri for an image to show in the notification, a subject string and a content string. After that, I wire to the onshow event a setTimeout function to cancel the notification. The show function which is used last will display the notification to the user. In the specification, you can also use the Notification object and instantiate it with the same parameters.

The createNotification is coming from WebKit engine implementation.

The Full Example

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Notifications</title>    
    <script type="text/javascript" 
    src="jquery-1.6.2.min.js"></script>
</head>
<body>
    <div>
        <input id="btnGrantPermission" 
        type="button" value="Grant Notification Permission" />
    </div>
    <script type="text/javascript">
        $(document).ready(function () {        
            if (window.webkitNotifications) {
                window.Notifications = window.webkitNotifications;
                $('#btnGrantPermission').click(function () {
                    if (window.Notifications.checkPermission() == 0) {
                        createNotification();
                    } else {
                        window.Notifications.requestPermission();
                    }
                });
            }            
        });        
 
        function createNotification() {
            var notification = window.Notifications.createNotification
            ("1.png", "New HTML5 Notification Received - Subject", 
            "More Content...");
            notification.onshow = function () {
                setTimeout(notification.cancel(), 15000);
            }
            notification.show();
        }
    </script>
</body>
</html>

A few things to pay attention about the sample:

  • I remove the webkit prefix since in the specifications it doesn’t exists. It will be omitted when the specifications will be a recommendation (I hope…).
  • The sample will work only in browsers that use WebKit engine such as Google Chrome.
  • I use jQuery to add event listener to the click event.

Here is the notification that you’ll get when you use this piece of code:

Notification

Summary

Web Notifications API can add more power for web developers by helping them to create simple notifications to their clients when things like arriving mail, event alert and more happens in the web application. The specifications are currently in working draft so they might change in the future. Moreover, only the browsers that use WebKit engine implement it currently so it is very early to adapt this API.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
QuestionNot Working Pin
Arslan Elahi23-Dec-13 2:48
professionalArslan Elahi23-Dec-13 2:48 
QuestionNot worked for me. Pin
Priyank Bolia2-Aug-11 20:19
Priyank Bolia2-Aug-11 20:19 
AnswerRe: Not worked for me. Pin
Gil Fink3-Aug-11 18:37
Gil Fink3-Aug-11 18:37 
AnswerRe: Not worked for me. Pin
axpicasso12-Oct-12 5:56
axpicasso12-Oct-12 5:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.