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 in 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 in 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


Contents

  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>
</div>

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

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

 function timerHandler() {
  count++;
  $('#seconds').text(count);
 }

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

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

2. Conclusion

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

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *