Desktop Notification Like Gmail using HTML5

Desktop notification is a way to notify user about important events even if the browser or tab is inactive or minimized. This increase the user experience and also keeps the user engage with your applications.

In this tutorial i am going to show you how to develop Desktop notification system using core HTML5 and JavaScript.

LIVE DEMO DOWNLOAD

Some famous applications already using Desktop notification like Gmail using it to notify new email received. Facebook use it for notifying user about any activity such as if any one commented on your post it or like it.

Note : Facebook have Desktop notification as well as internal notification system which works in the facebook tab only. Don’t mix both of them, they are different.

Design:

I have developed a Desktop notification which look like this. In this we have option to put icon, title and body text.

notification

Code:

Creating a Desktop notification is as easy as the line of code shown below.

var notification = new Notification("I am Desktop Notification");

You can pass arguments to Notification function and they are as follows:

  • title: Title of notification
  • body: Content of Notification.
  • icon: Icon path (URL,image or blank).
  • tag : ID of notification.
  • dir: Direction of Text. (left,right,auto)

Complete JavaScript code:

<script>
function notifyMe() {
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }
  else if (Notification.permission === "granted") {
        var options = {
                body: "This is the body of the notification",
                icon: "icon.jpg",
                dir : "ltr"
             };
          var notification = new Notification("Hi there",options);
  }
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      if (!('permission' in Notification)) {
        Notification.permission = permission;
      }
   
      if (permission === "granted") {
        var options = {
              body: "This is the body of the notification",
              icon: "icon.jpg",
              dir : "ltr"
          };
        var notification = new Notification("Hi there",options);
      }
    });
  }
}
</script>

To trigger a Desktop notification, here is a HTML code. Put this under <body> tag.

<button onclick="notifyMe()">Notify me!</button>

Explanation:

if you look over the JavaScript code then you might notice that code runs after doing some important validation. Those validations are performed in order to ensure that application using Desktop notification runs under the sandbox defined by browser.

Step 1: Checking whether browser support Desktop notification or not.

Step 2: Checking if permission is already granted (means it is not a first visit.), if it is then show the notification.

Step 3: Checking if permission is not “denied” by user externally, then requesting browser to confirm the permission.

    Notification.requestPermission(function (permission) {
      if (!('permission' in Notification)) {
        Notification.permission = permission;
      }

Step 4: If user allow the permission then we will show the notification else not.

Running the code:

You can download the code by provided link and make sure you run it by Web Server. If you will directly run it like static HTML then you will probably not get the output. Place it in HTDOCS folder and access it via URL.

Once you will click on the button, Browser will ask you for permission. Allow it and then see the output on bottom-right of Desktop.

permission

Further Reading:

Example above is static. You have to click a button and it will show you the notification. Real time application need more than this. So let’s discuss one real time example with Desktop notification.

For example you are building an email reader app by having Node as backend and angular as front-end. You have timer job running which checks for arrival of new emails in database. You can use Notification in real time app like the one shown below.

var app=angular.module(‘show_new_mail’,[])
.controller('email_control',function($scope,$interval,$http){
      var timer=$interval(function(){
     
       $http.post(“API to check new emails”,function(data){
                //just assuming that data consist of every parameter we used below.
               //Also desktop notification is enabled in setting of app.
                if(data.new==1)
               {
                         var options = {
              body: data.email.excerpt,
                  icon: "icon.jpg",
                          dir : "ltr"
                    };
                       var notification = new Notification(data.email.title,options);
                       //onclick do some action, like redirect or new window
        notification.onclick=function(){
};
//on display of notification do some action like play sound
notification.onshow=function(){
};
               }
               
       });

      },100);
});

You can see the complete specification here.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

27 Comments

  1. Wow its a simple and great method for desktop notification. I wonder with the javascript.
    I have one doubt that how can i limit the number of notifications shows.(by default its 4 and if more notifications are queued when i close the first one the next will append in bottom). How can i show notification only one window and when new notification comes it replaces the first one and shows the latest one ?

    1. Hi Vishnu,
      As far as i know there is no built in support for that. However i think you can do using ondisplay() listener. In the block of ondisplay() just close other notification using close() method. Give it a shot !

  2. Thanks for the such wonder full and use full module.
    i have one confusion. is there any way to display notification as per our required time?. i.e. I want to display notification until user not close it. how it’s possible?

  3. Hi there, thanks for the tutorial.
    My question is the same as Vishnu Prasad.
    Can you show us how to make only one notification show up on the screen?
    Every time that a new notification comes, it would replace the notification that is already in place.
    I’m using it on my project, but i don’t know how to change it.

    Thank you.

    1. Hi
      I succeeded in showing the notification one at a time. When a new notification came it overwrites the old one like “gmail”
      Here is my code

      var notification = null; //set null before notification came

      function notifyMe() {

      try{ notification.close(); } catch(e){ } // it closes the notification if present

      //**** rest-of-the-codes-as-same-***//

      }

      Here when new notification came the old one closes and new one opens.

      Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification

      I think it may help.

  4. AutoClose

    var notification = new Notification(“WARNING BLA”,options);
    setTimeout(function(){ notification.close(); },3000);

  5. Hi Shahid,

    This was awesome and so much helpful for my project after searching a lot.
    Here i need to open the parent window when i click the notification and the notification to be disappear.

    Pls help me with this and how can i control the notification count to 1 instead of three.

  6. Hi,

    This simple feature is awesome,
    One thing i want is to remove the web app server url from the notification,
    Is is possible to remove web app server url ??? if yes how ???

  7. hi,

    How can I add style to it, and what is bootstrap notify.js and other notify.js on GitHub

    this code works without any library , so what Can I do to add the style element for these notifications

  8. can i use this code for notify my user if they have some approval to do once i post something into database ? do you have an example approach ?

    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *