JavaScript: How to return True if the focus is on the browser tab page?

In this article, we will learn to check if the browser tab page is focused and under use or not in JavaScript. This is mainly required to record the user's inactivity time on the app and then take any action upon it if required.

Use Cases for Monitoring Browser Tab Focus

Following are the use cases for monitoring browser tab focus and user inactivity:

  • Prevent sending network requests if the page is not being used by the user as this reduces server traffic.
  • Save server costs by reducing unnecessary resource consumption.
  • Monitor time spent by each user and calculate statistics based on these values.

Different Approaches

Following are the two different approaches to check if the browser tab page is focused:

Using Page Visibility API

The Page Visibility API is provided by HTML5 which lets developers know if the tab is currently visible or not. The API sends a visibility change event when the user minimizes the window or switches to another tab.

Key Properties

document.hidden: This property returns false when the current tab is visible, otherwise it returns true.

<!DOCTYPE html>
<html>
<head>
   <title>Check Tab Focus</title>
</head>
<body>
   <h2 id="status">Tab is currently visible</h2>
   <button onclick="checkVisibility()">Check Visibility</button>

   <script>
   function checkVisibility() {
      const status = document.getElementById('status');
      if (document.hidden) {
         status.textContent = 'Tab is hidden';
         status.style.color = 'red';
      } else {
         status.textContent = 'Tab is visible';
         status.style.color = 'green';
      }
   }

   // Listen for visibility changes
   document.addEventListener('visibilitychange', function() {
      checkVisibility();
   });
   </script>
</body>
</html>

Example: Background Color Change on Tab Switch

<!DOCTYPE html>
<html>
<head>
   <title>Page Focus Detection</title>
   <style>
   .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 style="text-align: center;">
   <h1 style="color:green;">Welcome To Tutorials Point</h1>
   <h2 id="txt">Switch tab to change the background color.</h2>
   <div class="btn_container">
      <button id="btn">Original Color</button>
   </div>

   <script>
   const ogcolor = "white";
   const newcolor = "#C0C0C0";
   const txt = document.getElementById("txt");
   const btn = document.getElementById("btn");

   document.addEventListener("visibilitychange", function() {
      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>
</body>
</html>

Using window.onfocus and window.onblur Events

These events are useful in JavaScript for detecting when a browser window or tab gains or loses focus. They help developers trigger specific actions based on whether the user is actively interacting with the page.

  • window.onfocus ? Fired when the tab receives focus.
  • window.onblur ? Fired when the tab loses focus (user switches to another tab).

Basic Usage

<!DOCTYPE html>
<html>
<head>
   <title>Focus/Blur Detection</title>
</head>
<body>
   <h2 id="focusStatus">Tab is currently focused</h2>

   <script>
   const status = document.getElementById('focusStatus');

   window.onfocus = function() {
      status.textContent = 'Tab is focused';
      status.style.color = 'green';
      document.body.style.backgroundColor = 'white';
   };

   window.onblur = function() {
      status.textContent = 'Tab lost focus';
      status.style.color = 'red';
      document.body.style.backgroundColor = '#f0f0f0';
   };
   </script>
</body>
</html>

Complete Example

<!DOCTYPE html>
<html>
<head>
   <title>Page Focus with Focus/Blur</title>
   <style>
   .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 style="text-align: center;">
   <h1 style="color: green;">Welcome To Tutorials Point</h1>
   <h2 id="txt">Switch tab to change the background color.</h2>
   <div class="btn_container">
      <button id="btn">Reset Color</button>
   </div>

   <script>
   const ogcolor = "white";
   const newcolor = "#C0C0C0";
   const txt = document.getElementById("txt");
   const btn = document.getElementById("btn");

   // Detect when tab loses focus
   window.onblur = function() {
      document.body.style.backgroundColor = newcolor;
      txt.innerText = "Background color changed - tab lost focus!";
   };

   // Detect when tab gains focus
   window.onfocus = function() {
      document.body.style.backgroundColor = ogcolor;
      txt.innerText = "Welcome back! Tab is now focused.";
   };

   // Reset button functionality
   btn.addEventListener("click", function() {
      txt.innerText = "Switch tab to change the background color.";
      document.body.style.backgroundColor = ogcolor;
   });
   </script>
</body>
</html>

Comparison of Methods

Method Event Trigger Browser Support Best For
Page Visibility API Tab visibility change Modern browsers Detecting tab hidden/visible state
focus/blur Events Window focus change All browsers Detecting window focus state

Practical Applications

<!DOCTYPE html>
<html>
<head>
   <title>Practical Tab Focus Usage</title>
</head>
<body>
   <h2>User Activity Monitor</h2>
   <p id="status">User is active</p>
   <p>Inactive time: <span id="inactiveTime">0</span> seconds</p>

   <script>
   let inactiveTimer;
   let inactiveSeconds = 0;
   const statusElement = document.getElementById('status');
   const timeElement = document.getElementById('inactiveTime');

   function startInactiveTimer() {
      inactiveTimer = setInterval(() => {
         inactiveSeconds++;
         timeElement.textContent = inactiveSeconds;
      }, 1000);
   }

   function stopInactiveTimer() {
      clearInterval(inactiveTimer);
      inactiveSeconds = 0;
      timeElement.textContent = '0';
   }

   // Using Page Visibility API
   document.addEventListener('visibilitychange', function() {
      if (document.hidden) {
         statusElement.textContent = 'User is inactive (tab hidden)';
         statusElement.style.color = 'red';
         startInactiveTimer();
      } else {
         statusElement.textContent = 'User is active';
         statusElement.style.color = 'green';
         stopInactiveTimer();
      }
   });
   </script>
</body>
</html>

Conclusion

Both the Page Visibility API and window focus/blur events provide effective ways to detect browser tab focus. The Page Visibility API is more modern and specifically designed for tab visibility, while focus/blur events offer broader browser compatibility. Choose the method that best fits your application's needs and browser support requirements.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements