Web Notifications

Feb 6
 
Web Notifications

Google Chrome has recently updated their stable release with some extra goodies; probably most notable is the inclusion of @font-face support which is very welcome. Another not so well know proposal by the Chromium team is to have web notifications which was shipped with the stable release (v4.0.249.78).

Web Notifications allows users to get updates on a webpage even if they’re not looking at it, shown to them through small notification boxes, think growl. This opens up some great potential for the current web apps out there. When you get a new email it could popup a little notification much like our desktop email clients do now or your twitter page could let you know when new @replies have come in, the possibilities are endless.

Interaction with your web app no longer needs the focus of the user to be informed that something has occurred, I know I would find notifications very useful.

Since this is a proposal and neither a working draft nor an agreed upon API, anything written about in this article is almost guaranteed to change. I will however try to make updates when changes are made. We have our first bug. If you’re using the latest dev version (5.0.317.2) Web Notifications will crash the browser, all previous versions still work fine.

Update: Web notifications spec has been updated see here for changes.

You’ve got mail

I’ll go through a few examples I have put together on how to setup and start using notifications today.

First example of Web Notifications in Chrome
This is what a notification looks like using the createNotification() method

Everyone loves the classic “you’ve got mail” voice, so let’s go through how to do that with Chromes Web Notifications.

TCNWN.myNotifications = window.webkitNotifications;
 
TCNWN.setup = function() {
    if(TCNWN.myNotifications.checkPermission() === 1) {
        // 1 = Permission is uknown so we request permission
        TCNWN.myNotifications.requestPermission();
    } else if(TCNWN.myNotifications.checkPermission() === 0) {
        // 0 = Permission has been granted to show notifications
    } else {  
        // 2 = Permission has been denied	
    }
};

A few things are happening here, for notifications to ever work you need to ask the user for permission. So we use the checkPermission() method to see what status web notifications are in and act on the status accordingly. Once permission has been granted notifications can then be used. Update: checkPermission() has been changed to permissionLevel() in the spec, this hasn’t been pushed out in any release of Chrome so checkPermission() still works.

A bizarre bug with web notifications is asking for permission by calling the requestPermission() method within the page will throw a security exception and won’t display the permission window where the user can either deny, allow or ignore the notifications request. To get around this I have to run the requestPermission() method as either a javascript: URL as this code only works when run in the address bar a javascript: link or by using an onclick function, but still cannot be called programatically (see Issue 31736). That’s why you need to click the first link in the demo. Once permission has been granted we no longer need to resort to that god awful hack, hopefully this is fixed ASAP. You’ll also notice the notifications object is prefixed with webkit, for similar reason why they prefix new CSS3 properties.

Once permission is allowed the requestPermission() method has a callback parameter where we can setup all our notifications. In this case we pass a function to display our got mail message.

TCNWN.gotMail = function() {
	if(TCNWN.myNotifications.checkPermission() === 0) {
		TCNWN.notification = TCNWN.myNotifications.createNotification(
			"http://www.thecssninja.com/demo/web_notifications/icon.png",
			"You've got mail",
			"The CSS Ninja has sent you an email"
		);
		TCNWN.notification.ondisplay = function() {
			var audio = new Audio("youvegotmail.mp3");
			audio.play();
			window.setTimeout("TCNWN.notification.cancel()", 5000);
		}
		TCNWN.notification.show();
	} else {
		alert("You need to allow web notifications for this to work");
	}
};

In the callback function we create our new notification object using createNotification() method which accepts an icon url, title and body text. To display nothing for any one of these parameters passing in empty quotes (“”) will work, otherwise it will display undefined. We then attach an ondisplay event listener so we can run some code when the notification displays. For this demo we load an mp3 to play “you’ve got mail” using HTML5 audio. We then create a setTimeout function to close the notification after 5 seconds. Lastly we execute the show() method so the actual notification displays.

Custom notifications

Along with the createNotification() we also have the createHTMLNotification() method which allows us to pass an url to a html page to be displayed as the notification. The second example on the demo page will load a notification that fetches a new tweet every 15 seconds and dynamically updates the content.

The second example using custom notifications method
Using createHTMLNotification() method, we can pass a url to be loaded in the notification window

TCNWN.loadTweet = function() {
    if(TCNWN.myNotifications.checkPermission() === 0) {
        TCNWN.notification = TCNWN.myNotifications.createHTMLNotification(url);
        TCNWN.notification.show();
    } else {
        alert("You need to allow web notifications for this to work");
    }
};

The only difference here is we specify 1 parameter for the createHTMLNotification() method which is the url for the notification we wish to display. I won’t be going into detail on loading the tweets, to touch on it quickly it uses a JSONP call.

Some observations

Since playing around with this and trying to figure out how it works I have come across some quirks/bugs.

If you go to the first example that does the “you’ve got mail” notification and click back in the browser before the audio finishes playing, it will stop the audio and the setTimeout function that closes the notification will never fire.

As discussed earlier in the article you can’t actually request permission to display web notifications from within your code, you have to create a javascript: link that will execute the code. I tried programmatically changing the window.location to a JavaScript url which would fire the requestPermission() method but that wouldn’t work.

Bringing focus back to the window that called the notification, as stated in the proposal by using window.opener.focus(), doesn’t currently work.

Finally the last quirk I came across with the twitter demo is that for some tweets with long unbroken strings it will cause the notification window to flicker uncontrollably. Setting white-space: pre-wrap to force long string to be broken can help fix the issue.

Looks promising

Web notifications do look like a promising addition to the browser land and can create some really useful feedback to a user. With today’s web applications pushing the limits of the current technology available in the browser, I’m sure many developers will embrace web notifications in clever and exciting new ways.

 
 

Post filed under: html5, javascript.

Skip to comment form.

Comments

  1. Hi,
    thanks for these posts which are very helpfull.

    Are These features currently experimented and only available on webkit?

    Safari uses webkit so why these examples do not work on it and just on chrome?

    phish, March 25th, 2010
  2. Yes, web notifications is still very experimental and the spec is currently in discussion on the web-apps mailing list.

    Google is the main driver behind this implementation and has only done the changes to their chromium build. I’d imagine it won’t be merged back into the main webkit trunk until it is more refined and there is at least a consensus about how it should work.

    The Css Ninja, March 26th, 2010
  3. It doesn’t work on MAC OS X yet, but it creates many great features to come! Excited about it.

    jkulak, March 27th, 2010
  4. Very helpfull article! Been playing with this code and was wondering if you can call the notification function when something is posted on your blog. Have tried to implement this in my wordpress but when updating or posting a new post, the javascript function isn’t called. Any thoughts on that issue/idea?

    Dries, May 27th, 2010
  5. @Dries – That sounds like a tricky implementation. You would have to have localStorage on a users computer keeping a record of what posts they’ve seen and if there are any new ones. From there execute a function to show a notification. Running the function could happen onload of the page which could run on every page view.

    The Css Ninja, July 5th, 2010
  6. @Dries/Ninja: Maybe combine a timer with AJAX to run a query on the wordpress db. Every post/revision has an ID, so you could use localStorage with onLoad to store the most recent post ID, and then every x amount of seconds, query the db and see if there are any ID’s higher than the one stored in localStorage -if so, shoot out a notification. Seems pretty straight forward. I haven’t tested it, but I don’t see why that wouldn’t work. You could even go as far as testing if post_name contains “revision” and alert viewers that a post has been updated, versus just newly created posts.

    Awesome idea Dries. If I have time to work on it I’ll post an update here.

    Kyle A. Matheny, December 24th, 2010
  7. @Kyle – Sounds like it could work, would be interested to see a working example. Keep us posted.

    The Css Ninja, December 24th, 2010
  8. Wow! That’s fantasic!! Is there any original code on this. Such as html5.

    Jamie, June 12th, 2011
  9. If you have two or more opened tabs, each tab want to show notification, how to avoid opening two or more same notifications?
    I have site with chat. New chat messages showed with notifications.
    I have to use `SharedWorker` to avoid opening two nofitications with same message. Are you have any idea how to implement it withou “SharedWorker” ?

    p.s.
    http://en.wikipedia.org/wiki/Race_condition

    Yaffle, June 20th, 2011

Trackbacks

  1. [...] GPS tracker on a Google Street View camera car … 2 Tweets Web Notifications | The CSS Ninja – All things CSS, Javascript & xhtml Web notifications allow developers to show small notification windows to users when certain [...]

    Most Tweeted Articles by javascript Experts, February 8th, 2010
  2. [...] This page… http://www.thecssninja.com/javascript/web-notifications [...]

    Communicating back to parent from a Webkit notification | DEEP in PHP, February 3rd, 2011
  3. [...] URL to webkitNotifications.createHTMLNotification(). I believe no other customization is available.http://www.thecssninja.com/javas…6:11amView All 0 CommentsCannot add comment at this time. Add [...]

    Is there a way to customize Chrome's desktop notifications? - Quora, March 10th, 2011
  4. [...] article for more information on how to add notifactions to users when thier not on your website:http://www.thecssninja.com/javas…im not sure if they have updated thier toolbar, im a safari fanatic :))1:34pmView All 0 [...]

    Could you describe a good high-level architecture for providing Chrome Desktop Notifications from a LAMP webapp? - Quora, March 19th, 2011

Leave a comment