Building useful notifications with HTML5 APIs

Many users keep loads of tabs open in their browsers these days. Stuff they're working on, things they want to read later, Twitter feeds. How is your site or application going to stand out anymore? What if you really want to draw a users attention? HTML 5 supplies us with a few JavaScript API additions that can help.

  • The Page Visibility API is the first. This allows you to get events if your application tab is moved away from the user but remains active.
  • The Web Notification API is the next. This allows you to create a pop-up that informs the user with your message.
  • Third is the Vibration API. It's a tiny API but it adds a physical aspect to notifications.

If you look at the supported platforms you'll see that the Page Visibility is supported on most current platforms. Web notifications are widely supported on desktop browsers, but mobile browsers unfortunately lack in support. Only the latest Android Browser supports it (not even Chrome for Android). Somewhat disappointing, I agree. The vibration API is better supported browser-wise (although not by iOS...) but -- as you probably imagined -- it's a lost cause on most desktops and laptops.

Support may vary, but that can only improve over time. So let's see how we can make the most out of it. First, I'll show you how to use the individual APIs.

Vibration API

I'll first blow you way with this awesome API. It allows you to make a user's device vibrate

//Make it vibrate for 300ms
window.navigator.vibrate(300);

//But you can define patterns as well... on, off, on times in sequence
window.navigator.vibrate([300,100,300])

Insultingly simple, I agree. One thing to note on the patterns though: I've found that for Android at least, the first buzz isn't always treated correctly. If you use the pattern in my example, you might notice that the first vibration is considerably shorter than the second one. You might want to experiment a bit with it to get the result you're after.

Page Visibility API

Next is a more interesting API. By registering your event handler to this you can get a signal whether or not your page is visible to the user. The example below is partially borrowed from MDN, but I tried to show which parts you'll need for which web browser.

// Currently different browsers have different events
var hidden, visibilityChange;
if (typeof document.hidden !== 'undefined') {
    // Opera 12.10, Firefox >=18, Chrome >=31, IE11
    hidden = 'hidden';
    visibilityChangeEvent = 'visibilitychange';
} else if (typeof document.mozHidden !== 'undefined') {
    // Older firefox
    hidden = 'mozHidden';
    visibilityChangeEvent = 'mozvisibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
    // IE10
    hidden = 'msHidden';
    visibilityChangeEvent = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
    // Chrome <31 and Android browser (4.4+ !)
    hidden = 'webkitHidden';
    visibilityChangeEvent = 'webkitvisibilitychange';
}

// Event handler: log change to browser console
function visibleChangeHandler() {
    if (document[hidden]) {
        console.log('Page is not visible\n');
    } else {
        console.log('Page is visible\n');
    }
}

//Register event handler
if (typeof document.addEventListener === 'undefined' ||
             typeof document[hidden] === 'undefined'   ) {
    console.log('Page Visibility API isn't supported, sorry!');
} else {
    document.addEventListener(visibilityChangeEvent, visibleChangeHandler, false);
}

This example will support almost all versions of browsers that have implemented the event. If you're looking to support only the most current browsers then you can do it much easier by registering the visibilitychange event. You can make it even easier on yourself by using the Visibility.js wrapper library which adds a hack to support older web browsers, should you need to.

As with the previous API, there are some notes to be made; desktop browsers will fire the event nicely when your tab loses focus. Unfortunately, you can't depend on the event if your user switches to an other application than the web browser. Switching apps on Android fires the event in Chrome, Firefox and Opera (sorry, no iOS for me).

Web Notification API

The first thing to note when you apply the web notifications API is that you'll need user consent to show a notification. This is probably better because your alerts could become annoying pretty fast, so respect your user by making sure notifications benefit, and don't pester, them.

Using the API requires us to look for different window elements because older browsers might have this implemented in a prefixed manner:

// Determine the correct object to use
var notification = window.Notification || window.mozNotification || window.webkitNotification;

// The user needs to allow this
if ('undefined' === typeof notification)
    alert('Web notification not supported');
else
    notification.requestPermission(function(permission){});

// A function handler
function Notify(titleText, bodyText)
{
    if ('undefined' === typeof notification)
        return false;       //Not supported....
    var noty = new notification(
        titleText, {
            body: bodyText,
            dir: 'auto', // or ltr, rtl
            lang: 'EN', //lang used within the notification.
            tag: 'notificationPopup', //An element ID to get/set the content
            icon: '' //The URL of an image to be used as an icon
        }
    );
    noty.onclick = function () {
        console.log('notification.Click');
    };
    noty.onerror = function () {
        console.log('notification.Error');
    };
    noty.onshow = function () {
        console.log('notification.Show');
    };
    noty.onclose = function () {
        console.log('notification.Close');
    };
    return true;
}

Here's what you'll see when you supply some text and an icon URL:

Notification example.

Combining them all

Let's see how we can combine these APIs together. I suggest the following scenario:

  • I'll assume you already have some sort of notification queue in your application that you can query.
  • We periodically query the back end for notifications to show.
  • We only push a notification if the page isn't visible and combine it with vibration, otherwise some foreground notification queue is assumed to show the notification.
  • If we can't send the notification, we fall back to changing the tab title so that we might get a user's attention.

Here's the code:

//Register event and requests permission
document.addEventListener('visibilitychange', visibleChangeHandler, false);
var notification = window.Notification || window.mozNotification || window.webkitNotification;
notification.requestPermission(function(permission){});

//Poll our backend for notifications, set some reasonable timeout for your application
window.setInterval(function() {
    console.log('poll...');
    jQuery.ajax({
        url: 'site/notifyQueue',
        dataType: 'json',
        data: {userid:'1234', token:'other data'},    //Include your own data, think about CSRF!
        success: function(data, status) {
            notificationPoster(data, status);
        }
    });
}, 5000);    //poll every 5 secs.

var originalTitle = '', messageCount = 0;
function notificationPoster(data, status)
{
    if (document['hidden']) {
        console.log('page not visible, use notification and vibrate');
        //Vibrate and try to send notification
        window.navigator.vibrate(500);
        if (false == Notify(data.title, data.body)) {
            //Fallback signaling which updates the tab title
            if ('' == originalTitle)
                originalTitle = document.title;
            messageCount++;
            document.title = '('+messageCount+' messages!) '+originalTitle;
        } else {
            //Notification was shown
        }
    }
    else {
        console.log('page visible, push to normal notification queue');        
        doYourOwnSignaling(data);

        //Reset fallback handling
        messageCount = 0;
        if ('' != originalTitle)
            document.title = originalTitle;
        originalTitle = '';
    }
}

Obviously, I've left out the actual notification implementation if the page is visible. That's outside of the scope of this tutorial. I do, of course, have some suggestions for that:

  • noty.js, which is available here on Binpress, has a simple interface which you can send your message to immediately.
  • Alternatively Notifier.js implements a very nice style that resembles the browser type notifications on screen.
  • Try Google, there are so many out there....

It's up to you really, you can implement it yourself or use one of the many libraries out there.

I hope these examples give you some inspiration to implement these APIs in your own application. Do let us know if this worked for you, or better yet, how you've improved it. Good luck!

0 comments


Or enter your name and Email
No comments have been posted yet.