Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a web notifications with Javascript

The tutorial explains how web notifications work in HTML and will guide you through steps to implement the same.

Introductions to Web Notifications

The web notification permits the user to show the notifications for given events and on user interactions irrespective of the tab it is focussing on.

The following steps can be made use of in order to implement notifications in just a few minutes:

Step 1: Verifying the Web Notifications Support

We need to verify whether the webkitNotifications is supported. The point to note here is the name of webkitNotifications which is because it is a part of a draft spec and you will see the final spec having notifications () function instead.

Listing 1: Code displaying the notification() function

// check for notifications support
// you can omit the 'window' keyword
if (window.webkitNotifications) {
  console.log("Notifications are supported!");
}
else {
  console.log("Notifications are not supported for this Browser/OS version yet.");
}

Step 2: Granting permissions to a user for a website to show notifications

You will see a security error being thrown due to any of the constructors that have been mentioned. The error will be thrown in case the user hasn't manually granted permissions to the website so as to show notifications. So as to handle the exception, make an attempt to make use of a try-catch statement. However one can also utilize the checkPermission method for the same purpose.

Listing 2: Handling the exception

document.querySelector('#show_button').addEventListener('click', function() {
  if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
    // function defined in step 2
    window.webkitNotifications.createNotification(
        'icon.png', 'Notification Title', 'Notification content...');
  } else {
    window.webkitNotifications.requestPermission();
  }
}, false);

In case you don’t a web application that doesn't have permissions in order to display the notifications, in that case you will have the requestPermission method showing the infobar:

Notifications Permission infobar

Figure 1: Notifications Permission infobar

The key point to remember here is that the requestPermission method only works in event handlers. These are the event handlers that are triggered by a user action. The user action could be mouse or keyboard events and this is done so as to avoid unwanted infobars. As far as this case is concened, the user action is the click on the button with id "show_button".

Not accessing the button will not make the above snippet work properly. The same will be the case when you don’t access the link that triggers the requestPermission at some point.

Step 3: Attaching listeners as well as Other Actions

Listing 3: Code attaching listeners

document.querySelector('#show_button').addEventListener('click', function() {
  if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
    // function defined in step 2
    notification_test = window.webkitNotifications.createNotification(
      'icon.png', 'Notification Title', 'Notification content...');
    notification_test.ondisplay = function() { ... do something ... };
    notification_test.onclose = function() { ... do something else ... };
    notification_test.show();
  } else {
    window.webkitNotifications.requestPermission();
  }
}, false);

One might want to encapsulate all these events and actions at this point and creating your own notification class so as to keep the code cleaner

Example

The example involves setting of the notification permissions for this page. However the point to note here is that, this button should be used in case you also want to reset the permissions.

How to display notification on background or new tweets?

You need to enter your user name in order to display your last three tweets in the notifications. The exception can be in the case where there's a retweet that is not returned by the twitter Application. In the backend, every minute there will be a check for new tweets.

For us to represent this tutorial with the way of an example, we are grabbing the tweets making use of JSONP and than coming up with a loop in order to display 3 of them.

It is worth noting over here is that we have a restriction on the number of notifications which is supposed to be displayed. This depends on the screen as well as the notification size. If you see about the average tends of the notification, it turns to be around 5. In case you have any new notification beyond 5, in that case it will be queued waiting for the current notifications to be closed.

Listing 4: Code displaying the process to fetch tweets

// Retrieve tweets using jsonp.
var script = document.createElement("script");
script.src = 'http://twitter.com/statuses/user_timeline/'+ username+'.json?' +
             'count=3&callback=fetchTweets';
document.body.appendChild(script);

function fetchTweets(data) {
  var tweet;
  var i = data.length;
  while (i--) {
    tweet = data[i];
    if (window.webkitNotifications.checkPermission() == 0) {
      window.webkitNotifications.createNotification(
          tweet.user.profile_image_url, tweet.user.name,
          tweet.text).show(); // note the show()
    } else {
      // Point to note here is that we can't call requestPermission from here for the reason that we 
      //  are in the callback function and not triggered just on user action
      console.log('You have to click on "Set notification permissions for this page" ' +
                  'first to be able to receive notifications.');
      return;
    }
  }
}

The main point here to be sure on is that we have tweet notifications being created on a callback function. In case there is a user who doesn't have permissions at that very moment, in that situation, it is not possible to display infobar that is seeking for permissions via the help of a requestPermission() method. As explained above, the method can only be triggered on a user action.

Conclusion

We learned today the technique on how web notifications work in HTML with a three step process. Hope you liked the article.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login