08 Jul

How to implement desktop notifications in your website

desktop-notification

In this tutorial you will learn how you can easily implement desktop notification using Javascript Notification Api.

The Notification Api allows alerting the user outside the context on a webpage.

Asking permission to show desktop notifications

 

Here, on page load we are asking permission from user to show desktop notification or not. Notification.permission property can have 3 possible values i.e

  • default: User has not been asked to allow/deny desktop notifications.
  • granted: User has granted permission to show desktop notifications.
  • denied: User has denied permission to show desktop notifications.

Note: Once user has denied permission, there is no way for the web applications to prompt user to ask for permission again .

Create a Notification

To create a notification, we basically  need  to provide two inputs, one is the title of notification and second an object which may contain following settings:

  • body: Specifies the text to be shown in notification body.
  • icon: URL of the icon to be show on notification.
  • lang: Specifies the language of notification.
  • dir: Direction of body’s text. Possible values can be auto i.e depends on browser settings, ltr i.e text will be shown left to right and rtl i.e text will be show right to left.

Binding Events

You can also bind events to a notification. There are basically 4 events supported i.e

  • onClick: Fires when a notification is clicked.
  • onClose: Fires when a notification is closed by the user or browser.
  • onShow: Fires when a notification is shown.
  • onError: Fires when an error occurs.

Let’s see how you can bind a click event to a notification to set focus on the browser tab that triggered notification.

Browser Compatibility

Chrome 22 and above, Firefox 22 and above, Safari 6+.
Not supported on Internet Explorer.

Hope you found this article useful :)
If you have any questions, please ask them in comments.

The following two tabs change content below.

Vineet Garg

Sr. Web Developer at GuestHouser
I am passionate about technology and web development.