Navarr's Tech Side The Technical Side of my Life

25Jan/101

Webkit JavaScript Notifications API

Something I learned about recently by following the updates being issued to Chrome, is that with today’s release they also pushed out the Webkit Notifications API to Chrome Stable (v4).  Surprisingly, this is actually the first I’ve heard of it’s existence.  I took a look and played around with it a bit, and it is qué cool.

Visit my Sandbox to see the code in action, or continue reading for some code excerpts.

One interesting thing about this new API is that it not only requires a user to authorize it, but in order for an authorization click to appear, the user has to do something.  You can’t make it appear as soon as the user visits the page, they have to click something or trigger an event.

For the sake of this example, lets say the user clicks a link that triggers the JavaScript function “notification();” and we want to show a notification onscreen.

function notification()
{
	if(window.webkitNotifications) // If we have the Notification API
	{
		var nc = window.webkitNotifications; // Set the API to nc for easy access
		if(nc.checkPermission()) // 1 = Not Allowed, 2 = Denied, 0 = Allowed
		{
			nc.requestPermission(myNotification); // Request Permission with a callback to myNotification();
		} else { myNotification(); }
	}
}
function myNotification()
{
	try
	{
		var nc = window.webkitNotifications;
		var notif = nc.createNotification(null,"Notification Title","Notification Body"); // Parameters: string URL_TO_IMAGE, string Title, string Body
		notif.show(); // Show Notification
	} catch(Err) {
		alert(Err.message); // Will output a security error if we don't have permission.
	}
}

As you can see from the code, its a fairly straightforward API for showing desktop notifications, and once the user has given the website permission, they can be triggered any time. Up to five notifications can appear, and the rest will be kept in a queue until the others are dismissed, either by the user or by calling .cancel(); on the notification variable (notif in this case).