Skip to content

Web Notifications API

Last updated on March 15, 2015

Web notifications API was designed to display END user notifications(desktop notifications), which allows alerting the user outside the context of a web page. This API is really very useful to show real time notifications like new email notifications, new tweet notification, new message notification ..etc, but the only thing we need to remember is the user interface of this notifications are not consistent, UI may very depending on the browser(FF,Google Chore..etc) and devices.

Here we are going to create the Notification object and using this object we will configure and display desktop notifications to the user.

Before writing some code, first run the feature detection test with if(window.Notification){ } .

Syntax :

var notification = new Notification(title, options)

Here :
title : The title that must be shown within the notification
options : An object that allows to configure the notification. It can have the following properties:

dir : The direction of the notification; it can be auto, ltr, or rtl
lang: Specify the lang used within the notification. This string must be a valid BCP 47 language tag.
body: A string representing an extra content to display within the notification
tag: An ID for a given notification that allows to retrieve, replace or remove it if necessary
icon: The URL of an image to be used as an icon by the notification

Example :

if(window.Notification && Notification.permission !== "denied") {
	Notification.requestPermission(function(status) { 
		var n = new Notification('Title', { body: 'I am the body text!' }); 
	});
}

Description of above lines:
1. Test Notification API browser support.
2. Request notification access from the user.
3. If the user allow to access notification API, the status comes back as granted.
4. If Status is granted create new notification object and pass title and options object to it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments