HTML5 Notification Example
In this example we are going to learn about HTML5 notification API.
For this example we will use:
- A computer with a modern browser installed.
- notepad++.
- Wamp Server: You can actually use any server, the most important thing is that your app has to be hosted on an http server or else HTML5 notifications will not work.
1. Getting Started
HTML5 notification API provides a way to notify or alert users outside the context of a webpage. HTML5 notification API is displayed at the system level. This means the way notification are displayed depends on the computer or device OS(operating system), just imagine the way desktop computers or mobile devices display notification. An HTML5 notification may appear in any of the following places:
- A corner of the user’s display.
- An area within the chrome of the user agent.
- The “home” screen of a mobile device.
Some of the important applications of this technology is in web based email systems or internet relay chat (IRC), where there is a need to notify users about new messages that has arrived (when the user is currently not using the browser application)
1.1 The Notification Object
We can create a new notification by creating an instance of the Notification
object. Let’s see how to do this below:
var title="New Notification";// title for the notification var options ={ body:"this is a new notification", icon:"pathtoicon/icon.jpg"//icon to display and it is optional } noti= new Notification(title, options);//instatiate the notification object.
1.2 Notification Permission
Before a webpage can send notifications it needs to be granted permission to do so. The user needs to grant the application permission at least once. The permission to display notification for a given origin can be one of three strings:
- default: This is equivalent to “denied”, but the user has made no explicit choice thus far.
- denied: This means the user does not want notifications.
- granted: This means notifications can be displayed.
You can check to see if you have permission by checking the value of the Notification.permission
read only property.
Notification.requestPermission();//it takes a callback function
Commonly, you’ll ask for permission to display notifications when your app is first initialized, and before trying to instantiate a Notification object.
Lets see a full example below.
noti.html
<!DOCTYPE html> <html lang=en> <head> <style> html, body{ width:100%; height:100%; margin:0%; font-family:"helvetica","verdana","calibri", "san serif"; overflow:visible; padding:0%; border:0%; } </style> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/> <title> Html5 Notification API Example </title> </head> <body > <script> window.addEventListener("load",c);// register an eventlistener for web page onload function init(){ var b=document.getElementById("but");//get the button object b.addEventListener("click",noti,false);//register an eventlistener for when user clicks the button } // function called when the web page has loaded function c(){ init(); if(window.Notification && Notification.permission!=="granted"){//check to see if notification is granted and notification is supported //if it is not supported request permission Notification.requestPermission(function(status){ if(Notification.permission!==status){ Notification.permission=status; } }) } } //function called when button is clicked and shows notification function noti(){ if(Notification.permission=="granted"){//check if we have notification permission var title="Just Testing This App";//title for notification var options={//options for notification body:"it is just a test" } noti= new Notification(title,options);//permission is granted, display notification } else{ alert("permission not granted");//alert error message : permission is not granted } } </script> <button id=but> Send Notification Now </button> </body> </html>
Note: inline JavaScript should be avoided because it makes the markup bigger and less readable. The content, structure and behavior are not well-separated, thus making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the Window object, thus polluting the global namespace.
In line 25 we register a web page onload event, which fires our function c()
when the web page is done loading. In line 32, inside the function c
we call the function init
. The init
function simply registers an onclick event listener for our button.
In line 32 (through an IF statement) we check if the browser running the code supports HTML5 notification. in that same line we check if the user has given the webpage notification permission. If the first condition returns true and the second condition returns false, we ask the user for notification permission(this is usually shown as dialog box with a message at the top and a yes and no button below.). If the “show me notification” button is clicked the noti
function is called. The function checks if the web page has permission for notification, if it has permission we show a notification else alert the user about the error.
1.3 Notification Events
Events can be fired on a notification instance. Developers can use these events to generate the required behavior.
- click: This event is triggered when a user clicks the notification.
- error: This event is triggered, when for some reasons the notification cannot be displayed.
These events can be tracked using the onclick
and onerror
handlers. You can also use the addEvenlistener
method on it.
1.4 Properties Of The Notification Object
- Notification.permission: It is a static property, this means it is only available on the notification Object and not its instance. It defines the current permission status and be either granted, denied or default.
- Notification.body: The body string of the notification as specified in the options parameter of the constructor.
- Notification.lang: The language code of the notification as specified in the options parameter of the constructor.
- Notification.tag: This represents the tag of the notification and it is declared or specified in the options parameter of the notification constructor.
- Notification.icon: This defines the URL of the image used as an icon of the notification as specified in the options parameter of the constructor.
- Notification.icon: This is the URL of an image to be displayed as part of the notification, as specified in the options parameter of the constructor.
- Notification.timestamp: This holds the time at which is created.
- Notification.title: This holds the title of the notification as specified in the first parameter of the constructor.
Your app can become a nuisance if it sends a lot of notification to the user in a short time. To avoid spamming the user with too much notification, it is possible to add a tag to a new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already been displayed, the previous notification is closed and the new one is displayed.
Lets take a look at an example below
noti2.html
<!DOCTYPE html> <html lang=en> <head> <style> html, body{ width:100%; height:100%; margin:0%; font-family:"helvetica","verdana","calibri", "san serif"; overflow:visible; padding:0%; border:0%; } </style> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/> <title> Html5 Notification API Example </title> </head> <body > <script> window.addEventListener("load",c);// register an eventlistener for web page onload function init(){ var b=document.getElementById("but");//get the button object b.addEventListener("click",noti,false);//register an eventlistener for when user clicks the button } // function called when the web page has loaded function c(){ init(); if(window.Notification && Notification.permission!=="granted"){//check to see if notification is granted and notification is supported //if it is not supported request permission Notification.requestPermission(function(status){ if(Notification.permission!==status){ Notification.permission=status; } }) } } //function called when button is clicked and shows notification function noti(){ if(Notification.permission=="granted"){//check if we have notification permission var title="Just Testing This App";//title for notification var options={//options for notification body:"it is just a test", tag:"notifications" } var i=0//counter variable //we generate a notification every 200 millisecond var timer =setInterval(function(){ noti= new Notification(title,options);//permission is granted, display notification if(i>7){//if the counter is greater than seven clearInterval(timer);// clear the timer } i++; },200) } else{ alert("permission not granted");//alert error message : permission is not granted } } </script> <button id=but> Send Notification Now </button> </body> </html>
2. Summary
In this example we learnt about HTML5 notifications. We learnt about HTML5 Notification object, its properties and methods. We also learnt how to use and work with this object.
3. Download the source code
You can download the full source code of this example here: html5notificationapi
what is ‘chrome of the user agent’