Most of the websites nowadays use Web Notification API be it Facebook, Twitter, Flowdock, Slack .... you name it. Ever wondered how does that happen? Wanted to implement it but difficulty and fear of learning curve were driving you away? Let me tell you its just a few lines of code even a beginner can understand and start writing. So do not hesitate start implementing it right away with me.

First and foremost we need to check if our browser supports Notification or not. You might be wondering everyone does why should I check it? This is web, you have n number of browsers in the market for each platform. We cannot know who supports it who doesn't. So prevention is better than cure and hence, I suggest check it before your users go bananas on different browsers. Also, the best way to test these codes is to keep typing everything on browser console right away.

if ('Notification' in window) {
  alert("Congrats you are using a modern browser and it supports Notification");
}

Note: Currently for mobile devices, this is supported by Android only which too is not a core Web Notification API but a hybrid version of WebKit. Click on Can I Use Web Notifications to know about supported platforms and browsers.

Next, we need to request for permission to allow Notification on the browser for our website. Remember following pop ups on mobile and desktops for Facebook?

enter image description here enter image description here

Yes, that is exactly what this part of the code is going to do. Just remember if the user blocks the Notification from your domain there is no way you can ask him again to allow Notification access unless he/she is desperate for your Notifications and he/she decides to go to settings and manually allow Notification from the browser. Here are the links Chrome Firefox to do that if in case you wanna do it manually for some of the domains that you blocked earlier. Let's look at the code now

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

Now that's fine but how do I show my Notification pop up and its contents? That's exactly what we will look now. Let's see

FYI: Web Notifications are not part of your website, they are browser specific features and are designed to look and respond in certain ways by different Browser manufacturers. Some browsers show it at the right bottom or some might show at the right top. Some might format it differently on Linux and differently on WIndows or Mac or Android. So do not expect your CSS skills to apply here.

The browsers need to support service workers to support this as Notification API runs in background on a different thread so that it can show Notification outside of your webpage.

I'll start with the code now and explain each of the parts later

  desktopNotification: function(data){
    if(Notification.permission === "granted") {
      var text = data.message;
      if(data.category === "message"){
        let user = this.get('store').peekRecord('user', data.author_id);
        text = "New "+data.category+" from "+user.get('firstName')+" "+
            user.get('lastName')+"\n"+ data.message ;
      }
      this.sendDesktopNotification(text);
    }
  },

  sendDesktopNotification: function(text){
    let notification = new Notification("Jack Woltz's Web Page", {
      icon: 'https://resizing.flixster.com/msQKJ4evvDtNOapCsKgFbTEBFVQ=/300x300/v1.bjs1MzcyNTk7ajsxNzQyMTsxMjAwOzE5MjA7MTA4MA',
      body:  text,
      tag: 'soManyNotification'
    });
    //'tag' handles muti tab scenario i.e when multiple tabs are open then only
    // only one notification is sent

    notification.onclick = function () {
      parent.focus();
      window.focus(); //just in case, older browsers
      this.close();
    };
    setTimeout(notification.close.bind(notification), 5000);
  }
  • Notification.permission There three permissions available for Notifications API which is non-editable and its value is made available by browser depending on if the user has allowed Notification for your domain or blocked or didn't do any anything. Following are its possible values:

denied — The user refuses to have notifications displayed. granted — The user accepts having notifications displayed. default — The user choice is unknown and therefore the browser will act as if the value were denied.

So if I have permission from the user to display notifications I will create a text that I need to display on the Notification pop up.

  • Text for Notification It is kind of Body for the Notification if you consider it as an HTML page. So you might be wondering where is the title tag if we have a Body like a tag for Notification. That's where we'll head next but first, let's understand what is text content. I have used the code for my project which will check if the data category is message(as I do not need another category of data in Notification) then I need to format it like "New Offer from Vito Corleone" + "\n"+"I'll make you an Offer you cannot refuse." This will look like this:

                                                                           ![enter image description here][6]
    
  • Notification Instance Now that we know what text needs to be displayed and if we have permission to display the Notification or not let's create the Notification and show it on the browser. new Notification("Jack Woltz's Web Page", { key:value, ...}) is the code that creates Notification instance and once you do that the Notification pop will instantly appear on the Browser.

i. Title: The 'Notification' constructor's first parameter is the title of the Notification which you can see in the screenshot is "Jack Woltz's Web Page". Mostly this name of our Domain or App. It is slightly bigger than the actual body of the Notification.

ii. Icon: In the list of parameters, you will see the first key is the icon, which should be an icon of your app. You just need to provide its URL and we do not have much control over this like all components. You just set the text or image and no styling.

iii. Body: This is the actual content of the Notification as I mentioned before. This is the text that we need to display after the title. Its font size is a bit smaller to differentiate it from the title.

iv. Tag: 'soManyNotification' : This is used mainly to avoid multiple pop ups from the same domain if you have them open in multiple tabs. Imagine having 5 tabs of an app open then you wouldn't want to see 5 Notifications right? That is exactly what this will prevent.

v. Domain name: The footer of the Notification is you domain URL which is read only and is fetched by the browser by the url. You cannot change it.

The above components are enough to display the Notifications, now we need to deal with actions after the Notifications are displayed like how long does it display and what happens after the user clicks on the Notification pop up. The latter part of the code does that two things specifically. the onlcick method is available to add actions after the user clicks on the Notification pop up.

notification.onclick = function () { 
  parent.focus(); 
  window.focus(); //just in case, older browsers 
  this.close(); 
};

This will bring the user to your app if the user clicks on the Notification pop up. You can also set this URL to some specific page like message inbox or notification page by using following code instead of window.focus():

window.open("https://en.wikipedia.org/wiki/The_Godfather")

  • notification.close

setTimeout(notification.close.bind(notification), 5000);

Now we need use setTimeout to set how long the Notification appears to the user. notification.close.bind() makes sure the close() call is associated with our Notification instance.

That's it. I know it's simple and you might be wondering why didn't you know this before. You know it now and make sure you don't forget to implement it on your app.

For more on this check the official documentation of Web Notifications on Mozilla

Your comment

*

*