418

Possible Duplicate:
Is there a way to detect if a browser window is not currently active?

I have a function that is called every second that I only want to run if the current page is in the foreground, i.e. the user hasn't minimized the browser or switched to another tab. It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.

Does anyone know how to tell this in JavaScript?

Note: I use jQuery, so if your answer uses that, that's fine :).

5

6 Answers 6

460

In addition to Richard Simões answer you can also use the Page Visibility API.

if (!document.hidden) {
    // do what you need
}

This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.

Learn more (2019 update)

12
  • 46
    +1 for giving an answer which doesn't rely on jQuery. This also seems like the best answer in the long run, as browsers move toward supporting W3C standards. David Walsh's example worked for me on Chrome and Firefox, but not Safari.
    – kronion
    Jan 4, 2014 at 22:38
  • 5
    Visibility and focus are completely different things. Jun 13, 2016 at 10:46
  • 11
    Page visibility API detects if the browser is visible, e.g not minimized or completely covered by another window. It doesn't detect the case where the window is visible but an another window is active. Jul 25, 2017 at 19:37
  • 3
    FYI: caniuse.com/#search=Page%20Visibility
    – James Haug
    Aug 9, 2017 at 16:09
  • 6
    @ckknight do you mind changing the accepted answer to this one? This updated answer is the one we should be using in 2019 May 22, 2019 at 14:12
378

You would use the focus and blur events of the window:

var interval_id;
$(window).focus(function() {
    if (!interval_id)
        interval_id = setInterval(hard_work, 1000);
});

$(window).blur(function() {
    clearInterval(interval_id);
    interval_id = 0;
});

To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:

$(window).on("blur focus", function(e) {
    var prevType = $(this).data("prevType");

    if (prevType != e.type) {   //  reduce double fire issues
        switch (e.type) {
            case "blur":
                // do work
                break;
            case "focus":
                // do work
                break;
        }
    }

    $(this).data("prevType", e.type);
})

Click to view Example Code Showing it working (JSFiddle)

13
  • does that works? tested? that simple?
    – mauris
    Nov 19, 2009 at 1:07
  • 9
    This answer is not optimal because focus and blur events can often fire more than one time in the browser for each conceptual Focus or Blur action taken by the user, in which case the client will start doing hard_work on more than one interval, basically simultaneously.
    – Jon z
    Oct 1, 2011 at 13:01
  • 3
    I've read elsewhere that onmousemove could be a viable replacement for focus. Sep 19, 2012 at 6:15
  • 1
    @MichaelRobinson Maybe for maximized/fullscreen tabbed browsers. It may still fire in Internet Explorer (bit-tech.net/news/bits/2012/12/13/ie-bug-cursor/1), although the focus is on some other application. Feb 13, 2013 at 15:44
  • 1
    But what if the user switches tab whilst the page loads, before $(window)focus/blur has been called? Depending on your use case, this might mess up the callback status, and any background job? (For example, if you start the background job on page load — but blur never happens, because the user switched tabs before $(window).blur was registered?)
    – KajMagnus
    Feb 22, 2013 at 11:58
168

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isTabActive;

window.onfocus = function () { 
  isTabActive = true; 
}; 

window.onblur = function () { 
  isTabActive = false; 
}; 

// test
setInterval(function () { 
  console.log(window.isTabActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

12
  • 1
    example is awesome. any idea about IE?
    – mauris
    Nov 19, 2009 at 1:19
  • 1
    I can confirm that it works great in IE7, haven't tested beyond that, this is the best answer and it was also the first answer among all the answers that are functionally the same, vote it up!
    – Jon z
    Oct 1, 2011 at 15:15
  • I also like this simple example. I have fixed a small typo and added page feedback + jquery to see what is happening without the console. jsbin.com/ulize3/80
    – B-Money
    Dec 23, 2011 at 16:54
  • 1
    for some reason isActive is always false on Chrome?
    – sri
    Jul 21, 2014 at 14:41
  • 7
    Actually, the reason it's always false on Chrome is because the console.log use window.isActive. Remove the window. part or add it everywhere. I also think isActive should be initialized as true for better results. Jan 9, 2016 at 20:52
21

Using jQuery:

$(function() {
    window.isActive = true;
    $(window).focus(function() { this.isActive = true; });
    $(window).blur(function() { this.isActive = false; });
    showIsActive();
});

function showIsActive()
{
    console.log(window.isActive)
    window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
    if (window.isActive) { /* do CPU-intensive stuff */}
}
1
  • This is the best answer of the whole lot, should have gotten much higher up votes.
    – Yee
    Apr 4 at 12:34
9

All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover() is the better choice:

$(window).hover(function(event) {
    if (event.fromElement) {
        console.log("inactive");
    } else {
        console.log("active");
    }
});

This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.

2
  • 2
    Good outside the box thinking; however, it wouldn't work very well if you were trying to figure out how long a user stays on a page. Also, hover is not a valid option for mobile browsers. To be fair though, I have no idea if the focus or blur event binding would work on mobile devices.
    – Edwin
    Apr 27, 2012 at 3:09
  • 1
    also, hover depends on a mouse move. if the tab was entered using a keyboard shortcut, then the hover is probably not triggered.
    – Kae Verens
    Jan 4, 2013 at 20:39
9

If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.

$(window).hover(function() {
  // code here...
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.