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.

11 thoughts on “How to Detect Browser Window is Active or not – JavaScript”

  1. When the pages have iframes this doesn’t workout.
    I mean when the focus is moved onto the iframe’s content, the window blur event will be called and then the timer would be stopped.

    Reply
  2. To check whether your site (on tab) is active or not, you could use like:

    setInterval(function () {
    console.log(document.hasFocus());
    }, 1000);

    Reply
  3. What do you think of Page Visibility API. This seems like a built in solution rather than keeping track with focus and blur events.

    Reply
  4. I came across your post about page animations, but I’m still unsure how to do it.  I don’t code by hand, but have been developing sites for a while, I just never got the hang of JS or JQuery, my patience level wasn’t quite there.

    My question is:  I’m using Webflow for a site.  I have a page animation, with multiple interactions.  After publish, the animation is fine if a stay on that tab.  If I click another tab or window, it’s weird.  The first part stops/pauses, but the other interactions keep going.  Upon returning, it’s a jumbled mess.  I’ve tested a few seconds, 10, 20, it’s all the same.

    I really wish I knew Javascript indepth.  I was hoping you could help me get a simple script or snippet to insert for this page.  

    I have completely finished the page, so it’s best I stop to figure this out.  If you need the site page let me know.  If it’s simple I’d appreciate your help, however if it’s too involved I don’t mind paying or contributing for the assistance.  I’m sure this issue will come up again as I finish the portfolio.

    If you have time, I can jump on a screencast… or just talk via email.  I sure hope you can help because I’ve sort of committed to this animation layout.

    Would this above code work for me?

    Reply
    • Instead of using setTimeout or set Interval for your animations, you should checkout requestAnimationFrame (rAF). It will stop animating when you move to another tab and restart appropriately – the added benefit is your animations become smoother too.

      Using the web native rAF directly might be daunting, but luckily there is this tiny library that you can use like you would use setTimeout and setInterval, but it handles using rAF for you — https://github.com/d3/d3-timer.

      It’s not my library, but I’ve used it in the past with great success and it has great code examples.

      Good luck!

      Reply
  5. hi sir i want to ask something i want to put a function on a specific time when timer reaches on specific time it stops and do that function kindly help me on this

    Reply

Leave a Comment