Display web notifications only when the browser window/tab is not active

HTML5 has brought with it the Notification API. In other words, HTML5 allow us to show browser notifications to the web app users. The most important feature is that the notification will be displayed regardless of which tab or window is focused.

That being said, personally I want to display a notification only when the source tab is not focused (actually,  that’s the desired behavior in most of the cases).
So, how can we display browser notifications only when the tab is not active/focused?

 //make sure the tab is not active/focused
 if(!document.hasFocus()) {
     showNotification('Hello world!');

//source: https://developer.mozilla.org/en-US/docs/Web/API/notification
function showNotification($message) {
    // Let's check if the browser supports notifications
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");

    // Let's check whether notification permissions have already been granted
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification($message);

    // Otherwise, we need to ask the user for permission
    else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
            // If the user accepts, let's create a notification
            if (permission === "granted") {
               var notification = new Notification($message);

 // At last, if the user has denied notifications, and you
 // want to be respectful there is no need to bother them any more.


Notification documentation on MDN

Browser compatibility

Official Notification API specs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s