Thursday, March 12, 2015

Web Notification API


Introduction:

The Notifications API allows you to display notifications to the user for given events, both passively (new emails, tweets or calendar events) and on user interactions regardless of which tab has focus.

HTML5 Web Notification allows you to configure and display desktop notifications to the users. The main purpose of Notification API is notifying the users outside the web page. For example, you may want to alert the user whenever there is a new email in the inbox. Do note that this feature was and is still experimental and not all the browsers currently support this.

The most popular use of this feature would be Gmail alerting you of new email, if you have a Gmail tab currently open. You will get an alert box pop up at the bottom right of the screen with the title and message inside. We are going to look at how you can use this API to create your own notification messages.

For Example as shown below:



Structure of the Notification API:

There are two objects to use in the Notication API the first is the notification object.
interface Notification : EventTarget 
{
 // display methods
 void show();
 void cancel();

 // event handler attributes
 attribute Function ondisplay;
 attribute Function onerror;
 attribute Function onclose;
 attribute Function onclick;
}
This is the interface you will use for the notifications, it has 2 methods and 4 attributes attached to it.

Notification Methods: The notification methods are used to display or hide the notification box.
  • Show - This method will display a notification.
  • Cancel - This will remove the notification, if the notification is currently displayed this will hide it. If the notification is not displayed then this will stop it from being displayed.

Notification Attributes: The notification attributes are used as event listeners on the different events on the notification.
  • ondisplay - A function to run when the notification box is displayed.
  • onerror - A function to run when there is an error with the notification box.
  • onclose - A function to run when the notification box is closed.
  • onclick - A function to run when there is a click on the notification box.

The second object needed for notifications is the NotificationCenter interface which is available to the webpage via the window interface.
interface NotificationCenter 
{
 // Notification factory methods.
 Notification createNotification(in DOMString iconUrl, in DOMString title, in DOMString body) throws(Exception);
 optional Notification createHTMLNotification(in DOMString url) throws(Exception);

 // Permission values
 const unsigned int PERMISSION_ALLOWED = 0;
 const unsigned int PERMISSION_NOT_ALLOWED = 1;
 const unsigned int PERMISSION_DENIED = 2;

 // Permission methods
 int checkPermission();
 void requestPermission(in Function callback);
}

interface Window {
...
 attribute NotificationCenter webkitNotifications;
...
}

The notification center is used to create notification objects and check that the webpage has permission to display the notification objects.
There are 4 methods that will need to use on the notification center:
  • createNotification - If the notification has permission to be displayed then this method will create a notification object populated with the content supplied to it. If the web page does not have permission to display the notification then this will throw a security exception.
  • createHTMLNotification - This is similar to the createNotification method it will return a populated notification if the webpage has permission to display the notification. This method uses a parameter of a URL to get the HTML to be displayed.
  • checkPermission - This will return an integer of the permission the notification has on this webpage. PERMISSION_ALLOWED = 0, PERMISSION_NOT_ALLOWED = 1, or PERMISSION_DENIED = 2
  • requestPermission - This will ask for permission from the user to display the notification box.

Construction of the Object:
var notification = new Notification(title, options);
Parameters:
Title
  • The title that must be shown within the notification

Optional:
An object that allows to configure the notification. It can have the following properties:
  • dir : The direction of the notification; it can be auto, ltr, or rtl
  • lang: Specify the lang used within the notification. This string must be a valid BCP 47 language tag.
  • body: A string representing an extra content to display within the notification
  • tag: An ID for a given notification that allows to retrieve, replace or remove it if necessary
  • icon: The URL of an image to be used as an icon by the notification


Get Started:
Step 1: Check for notification API support:
The below code will explain you the concept of API support, first it will dect if the browser is supported. If not then it will return the same. We check if the webkitnotification is supported. Note the name because the "webkitnotification" was the initial spec draft of notification API, the final spec now has Notification() function instead, it might give you false result but let us check!
//Check for notification support
//you can omit the window keyword

if (window.webkitnotifications)
{
   console.log("Notifications are not supported");
}
else
{
  console.log("Notifications are not supported for this browser/OS version");
}

You can also check if the Notification are supported on your browser version on caniuse.com.

Step 2: Request permission to allow notifications:
To display notification, user must first give permission to display any notification. to get permission box display, all you can do is to use the method requestpermission().

  
    /***
     ** Request notification permission
    **/
    Notification.requestPermission(function(permission)
    {
        //display notification here.
    });
  



Step 3: Display Notification:
When the button is clicked, we check if notification API is supported by the browser/OS, if yes, we proceed. The next step is obtaining permission as described above and creating a notification object. When the button is clicked the browser will ask for permission to display the notification, once accepted, it will display, and the subsequent clicks doesn't ask for permissions.

*Note: The HTML needs to be up on the server in order for the notification to work.





Close Notification Automatically:
In order to close notification automatically, we need to set timeout for the particular notification, it is as shown below.
var notification = new Notification("Hello, how are you?");
setTimeout(function(){
  notification.close();//Close the notification.
},2000);//time in milliseconds. 


Other Useful resources:
  • Vibration API: It's a tiny API but it adds physical aspect to the notifications. It allows you to make a user's device vibrate.
  • Page Visibility API: By registering your event handlers to this you can get a signal whether or not your page is visible to the user.
  • Notify.js: Notify.js is a jQuery plugin to provide simple yet fully customisable notifications. The javascript code snippets in this documentation with the green edge are runnable by clicking them.
  • Notifier.js: This easy to deploy script provides basic functionality of OSD/GNOME type non-blocking notifications on your webpages. There are four basic message types; Success, Warning, Error, and Info. As well you can create custom messages with ease.


Do Visit my GitHub for examples shown above.

Monday, February 9, 2015

Time to move ahead!

Hello Guys,

I appreciate all the people who read my blog and thank you for that. Moving ahead I completed my engineering, worked for a while and now moving ahead to pursue my masters in web development in canada. Hence I'll be posting some interesting stuff related to the web development topic as well as i found a new passion which i was aware of, technology stuff. 

Keep looking for more. Thanks again people.