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 the websites or PTC sites which provide ads viewing to the users. They only count the ads view when the user is active on their website until 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


  1. Example
  2. Conclusion

1. Example

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

  • focus  – for detecting active state, when this event trigger I start the timer
  • blur – for detecting inactive, state. From where I stop the timer by clearing the Interval.

On focus event, you can define your code which you want to execute when it is active and within blur event define which you want to do when it is inactive.

Completed Code

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

<!-- Script -->
<script type='text/javascript'>
 var count = 0;
 var myInterval;
 // Active
 window.addEventListener('focus', startTimer);

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

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

 // Start timer
 function startTimer() {
  myInterval = window.setInterval(timerHandler, 1000);

 // Stop timer
 function stopTimer() {

2. Conclusion

Within the example, I use it to count the number of seconds the user active on the website. You can also pause the playing video or stop some of the scripts when it is not using the website.

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