How to Detect Browser Window is Active or not – JavaScript

Sometimes you may want to take more control over your user Browser when he/she opens your website in a Browser Window.

For example – you want to know when the user closes the Browser Tab and execute your code.

If you want to know how much time the user active on your website, in this case, you can use JavaScript. Using that you only enabled the timer when the user is an active tab on your website.

Or you want to run the Animation only when the user is active otherwise stop it.

This kind of functionality you have seen on websites or PTC sites that provide ads viewing to the users. They only count the ads view when the user is active on their website until a given time otherwise they cancel the view after the specific time.

In this tutorial, I show how you can use JavaScript to detect whether Browser Tab Window is active or not.

How to Detect Browser Window is Active or not - JavaScript


Table of Content

  1. Example: Detecting Browser Tab Activity Status with JavaScript
  2. Conclusion

1. Example: Detecting Browser Tab Activity Status with JavaScript

For finding the Browser Tab is currently active or not I defined two events on window

  • focus  – This event signifies the active state. Upon its occurrence, I initiate a timer to keep track of user activity.
  • blur – On the other hand, when this event is triggered, it denotes an inactive state. At this juncture, I halt the timer by clearing the interval.

In the event of a focus, I trigger the startTimer function, initiating the countdown. Conversely, when the blur event transpires, indicating inactivity, the stopTimer function is called, terminating the countdown interval.

NOTE – Remember, within the focus event, you can implement the specific actions you desire when the tab is active. Similarly, within the blur event, define the behavior to be executed during periods of inactivity.

<div class='container'>
    Seconds : <div id='seconds'></div>
</div>

<!-- Script -->
<script type='text/javascript'>
 
var count = 0;
var myInterval;

// Active
window.addEventListener('focus', startTimer);

// Inactive
window.addEventListener('blur', stopTimer);

function timerHandler() {
    count++;
    document.getElementById("seconds").innerHTML = count;
}

// Start timer
function startTimer() {
    console.log('focus');
    myInterval = window.setInterval(timerHandler, 1000);
}

// Stop timer
function stopTimer() {
    window.clearInterval(myInterval);
}
</script>

2. Conclusion

In the provided example, I utilized this technique to calculate the duration of user engagement on the website, measured in seconds. Moreover, you have the option to pause a playing video or halt certain scripts when the user is not actively interacting with the website.

If you found this tutorial helpful then don't forget to share.