Using the web notifications API

Web notifications are one of the newer features added into modern browsers. They are intended as alerts for the user outside of the web page context. The idea is for them to be browsers intended, for example, when using a mobile browser notification could go into the home screen of the device. On the desktop usually they show up on the right-corner of the screen, at least on most desktop environments.

Using the web notifications API

Getting ready

For the purpose of this example, we will be using data derived from Project Gutenberg http://www.gutenberg.org/. The data are the tips from the chapter Use of spies from Sun Tzu's -Art of war and can be found in this recipe code example under data.json.

How to do it...

To create this recipe we will create an HTML file, and use jQuery for simplicity.

  1. First, we can start with the HTML part, where we just create a simple button and a div element with the ID fallback that we are going to use, if the browser does not support notifications.
    <body>
      <button id="show">Show quote</button>
      <div id="fallback" ></div>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
      <script src="js/notification.js"></script>
      <script src="js/display.js"></script>
    </body>
  2. Let's first create the notification.js file that we will use as utility to create simpleNotifations.show(data). The first check we have to do is verify support for webkitNotifications, the only full implementation at the time of writing.
    var simpleNotification = (function () {
      var my = {};
       my.show = function (data) {
        if (window.webkitNotifications) {
          //check if there is a support for webkitNotifications
          if (window.webkitNotifications.checkPermission()== 0) {
            var notification = webkitNotifications.createNotification(data.icon, data.title, data.body);
            notification.show();
            //set timeout to hide it
            setTimeout(function(){
            notification.cancel();
          }, data.timeout);
        } else {
          webkitNotifications.requestPermission(function () {
            //call the same function again
            my.show(data);
          });
        }
      }
  3. Next is the check for the real-standard-based web notification object, where in future, as browsers implement it more and more, it should be the first one.
    else if (window.Notification) {
      if ("granted" === Notification.permissionLevel()) {
        var notification = new Notification(data.title, data);
          notification.show();
        } else if ("default" === Notification.permissionLevel() ) {
          Notification.requestPermission(function () {
            //call the same function again
            my.show(data);
          });
        }
      }
  4. Finally the case; if there is no support for any type of notification by the system we just use a callback to handle this case, where we also close the utility.
      }else{
        //Notifications not supported, going with fallback
        data.errorCallback();
        }
      };
      return my;
    }());
  5. Next, we can continue with creating the display.js file that will get a random quote from the data, and call the previously defined simpleNotification.show() method. First we will do the fetching.
      function fetchRandomQuote(location,data){
        $.ajax(
          {
            url:location,
            dataType:'json',
            success: function(result){
              var quoteNumber = Math.floor(Math.random()*26)+1;
              var obj = result.quotes[quoteNumber];
              for(var key in obj){
                data.title += key;
                data.body = obj[key];
            }
           simpleNotification.show(data);
        }}
        );
      };
  6. Because we want some default behavior for all the notifications, such as icon, default message, or fallback function, we do the callout with a default data object.
    $(document).ready(function() {
      $("#show").click(function (){
        var data = {
          icon: "images/war.png",
          title: "The Art of War - The Use of Spies ",
          body: "text",
          timeout : 7000,
          errorCallback: function(){
            $("#fallback").text(this.body);
            }
          };
        fetchRandomQuote('js/data.json',data);
        });});

How it works...

We will take a deeper look at the notification.js file, where most of the notification logic is. The check tests we did on the notifications if (window.webkitNotifications) and if (window.Notification) try to see if there is such object in the browser. If no such object is there, this means there is no support for that type of notification. While on the other hand, if the if condition was met, this means we have support, and can ask for permission.

  if (window.webkitNotifications.checkPermission() == 0)

After that, we are free to create the notification and show it with the given parameters for icon, title, and body.

var notification = webkitNotifications.createNotification(data.icon, data.title, data.body);
notification.show();

If we want the notification to hide after a given timeout, we add the following function:

setTimeout(function(){
  notification.cancel()
}, data.timeout);

On the other hand, if we do not have the permission to display a notification, we need to request it from the user, where we can do the call to our function once again.

webkitNotifications.requestPermission(function () {
  my.show(data);
}

Tip

The request for the permission must come from a user-triggered event on some HTML element. In our case this is the onClick function on the button. More specifically the jQuery click $("#show").click(function (){ ...}.

We don't need to get into too much details for the fetching of the data, but in our default object we have the icon parameter with the value images/war.png that we will get used for the notification, as well as the fallback function and the timeout configuration.

var data = {
  icon: "images/war.png",
  title: "The Art of War - The Use of Spies ",
  body: "text",
  timeout : 7000,
  errorCallback: function(){
    $("#fallback").text(this.body);
    } };

Note

At the time of writing, Chrome is the only browser with full support for the notifications for quite some time, but Safari 6.0 and Firefox 22 Aurora also have initial implementations.

The full specifications for web notifications can be found from http://www.w3.org/TR/notifications/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.120.136