Open In App

How to return true if browser tab page is focused in JavaScript ?

Last Updated : 05 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There may be situations when we need to check if a browser tab is focused or not. The reasons for this include:

  • Prevent sending network requests if the page is not being used by the user as this would reduce the amount of load on the server. Also, this would save upon the cost if we are using a paid third-party API.
  • Stop playback of media when the tab is not focused.
  • Automatically pause an in-browser game when the user switches to another window or tab.
  • Many sites track the time period for which the user was actually interacting with the website using this functionality.

In this article, we will learn how to implement this functionality. We have the following two methods:

Using the Page Visibility API: HTML5 provides the Page Visibility API that lets the developer know if the tab is currently visible or not. The API sends a visibilitychange event when the user minimizes the window or switches to another tab. This API adds the following two properties to the document object and both properties are read-only.

The document.hidden property: This property returns false when the current tab is ‘visible’, else returns true. The visible keyword has a special meaning here. Suppose you open another small window on top of the current tab, the document.hidden would return false even though the tab isn’t in focus because the rest of the tab is still visible which is not covered by the small window. 

The document.visibilityState property: This property returns a string indicating the document’s current visibility state. Possible values are:

  • visible: The page content is visible or at least partially visible as explained above.
  • hidden: The page content is not visible to the user, either due to the document’s tab being in the background or part of a window that is minimized, or because the device’s screen is off.
  • prerender: The page has been loaded but the user has not viewed the page.
  • unloaded: The page is in the process of being unloaded from memory i.e. it is about to be closed.

Example: We will create a webpage that would change the color when the user switches tab or minimizes the window.

HTML




<!DOCTYPE html>
<html>
<head>
    <style>
        * {
            box-sizing: border-box;
            font-family: "Roboto", sans-serif;
        }
 
        html,
        body {
            height: 100%;
        }
 
        body {
            background-color: #f1f5f8;
        }
 
        #txt {
            text-align: center;
        }
 
        .btn_container {
            padding: 10px;
            text-align: center;
        }
 
        #btn {
            border-radius: 4px;
            cursor: pointer;
            padding: 4px 8px;
            background-color: white;
            font-size: 1.2em;
            letter-spacing: 1px;
        }
    </style>
</head>
 
<body>
    <h2 id="txt">Switch tab to change the background color.</h2>
    <div class="btn_container">
        <button id="btn">Original Color</button>
    </div>
</body>
<script>
    const ogcolor = "#f1f5f8";
    const newcolor = "#39a9cb";
    const txt = document.getElementById("txt");
    const btn = document.getElementById("btn");
 
    document.addEventListener("visibilitychange", function (event) {
        if (document.hidden) {
            document.body.style.backgroundColor = newcolor;
            txt.innerText = "Background color has changed !";
        }
    });
 
    btn.addEventListener("click", function () {
        txt.innerText = "Switch tab to change the background color.";
        document.body.style.backgroundColor = ogcolor;
    });
</script>
</html>


Output:

Using the window.onfocus and Window.onblur events:

  • window.onfocus: This event gets fired when the tab has received focus.
  • window.onblur: The blur event fires when the user minimizes the window, switches to another tab, or uses another window. The blur event gets fired even when we use another small window and the tab is still partially visible or even when we click on the location bar of the browser.

Example: We will create a webpage that would change the color when the tab looses focus. Here we will try to switch to another window and understand the difference between document.hidden and window.onblur.

HTML




<!DOCTYPE html>
<html>
<head>
    <style>
        * {
            box-sizing: border-box;
            font-family: "Roboto", sans-serif;
        }
 
        html,
        body {
            height: 100%;
        }
 
        body {
            background-color: #f1f5f8;
        }
 
        #txt {
            text-align: center;
        }
 
        .btn_container {
            padding: 10px;
            text-align: center;
        }
 
        #btn {
            border-radius: 4px;
            cursor: pointer;
            padding: 4px 8px;
            background-color: white;
            font-size: 1.2em;
            letter-spacing: 1px;
        }
    </style>
</head>
 
<body>
    <h2 id="txt">Do not loose focus!</h2>
    <div class="btn_container">
        <button id="btn">Original Color</button>
    </div>
</body>
<script>
    const ogcolor = "#f1f5f8";
    const newcolor = "#39a9cb";
    const txt = document.getElementById("txt");
    const btn = document.getElementById("btn");
 
    window.onfocus = function () {
        txt.innerText = "This tab is in focus!";
        document.body.style.backgroundColor = ogcolor;
    };
    window.onblur = function () {
        document.body.style.backgroundColor = newcolor;
        txt.innerText = "Lost focus, background color has changed !";
    };
    btn.addEventListener("click", function () {
        txt.innerText = "Switch tab to change the background color.";
        document.body.style.backgroundColor = ogcolor;
    });
</script>
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads