Here's an example of what it looks like (upper right corner)
The code is extremely simple, following a pattern of
- Check to see if the browser supports the feature (common with any newish feature)
- Check if you have permission to display notifications
- If not, request access
- On callback make sure we have permission (if we don't they denied access)
- Display the notification
if(webkitNotifications) // check that the browser supports notifications { if(webkitNotifications.checkPermission() === 1) // checkPermission returns 0 for allowed, 1 for not allowed { // requestPermission() accepts an option callback argument; if a function is presented it will run that after a user has // selected allow or deny webkitNotifications.requestPermission(function(){ if(webkitNotifications.checkPermission() === 0) { // user allowed notifications showNotif('Notifications enabled', 'Thanks for enabling notifications, guy.'); } else { // user declined notifications alert('we\'ll contact you some other way...'); } }); } else { showNotif('You\'re silly', 'You already had notifications for us enabled'); } function showNotif(title, message, img) { // if img wasn't specificed give it a default value img = img === undefined ? 'http://nerdforum.org/favicon.ico' : img; webkitNotifications.createNotification(img, title, message).show(); } }
That's it!
Here's a working example: http://jsfiddle.net/ah4hH/1/
I'm hoping browser support for this picks up, it's certainly a nice feature to have for a multitude of services. This combined with ajax polling can accomplish some neat things. (ie, desktop notifications for a new message or reply to a subscribed thread, etc.)
There are several pitfalls to be careful of, you can send an unlimited* amount of notifications but only 3 will be displayed, the rest placed into a queue. At the time of writing this you do not have access to the queue (outside of making one yourself), so if you wanted to avoid redundant notifications (IE multiple notifications for a new message from the same user) you need to make use of the notifications tag attribute. If two notifications with the same tag are sent only the most recent will display.
* I only tried 100, I can't imagine a case logically wanting to exceed that.
There's also a few useful events for the Notifications object,
onclick, onclose, ondisplay, onerror, onshow
Here's the w3c write up: http://www.w3.org/TR/notifications/
I'll probably make a neat little Notifications wrapper this afternoon.