DEVseo

Making It Your Web

Using The Web Notifications API

Firefox has just been updated to version 22, 6 weeks after the previous release of 21. There are lots of changes in the new version, but one of the most interesting for me is the native support for Web Notifications. I'm not one for reading specs though and wanted to dive right in so here's how to use the API quickly and easily.

In it's most simplest form, the following code will produce a Notification in Firefox:

var myNotify = new Notification("Test Title", {
	'body': "This is the body of the notification",
});

A notification in Firefox

That is literally all of the code you need! Lovely. However, there are some caveats. Obviously, the most important for security, and to prevent unwanted annoyances, you must first ask for permission to show a notification on a domain. But, it turns out this is a pretty darn easy thing to do too! See the following code:

var allowNotifications = false;
window.Notification.requestPermission(function (perm)
{
	switch (perm)
	{
		case 'granted':
			allowNotifications = true;
		break;
	}
});

And there you go! From this, you can do just about anything! But what about browsers that don't support Notifications? Well, you can easily do a check for the value of window.Notification and not do any of the above if the object doesn't exist. Or, you can go and grab this really handy wrapper from Alex Gibson that handles it all for you. Go forth and Notify! Below is the complete code from this example.

var allowNotifications = false;
window.Notification.requestPermission(function (perm)
{
	switch (perm)
	{
		case 'granted':
			allowNotifications = true;
			showNotification();
		break;
	}
});
function showNotification()
{
	if(allowNotifications === true)
	{
		var myNotify = new Notification("Test Title", {
			'body': "This is the body of the notification",
			'tag' : "",
		});
	}
}

Update: I have created a little example for you here.

Comments (be the first)

Add A Comment

Please note: all comments are moderated before they are published on this page.


91jti7
Cancel Reply

Loading

Complete!