5

I have looked at this:

How to tell if browser/tab is active

and:

Is there a reliable way to determine if a browser tab or window is inactive or not in focus?

The first link provides a solution for modern browsers but doesn't work in IE7/8. Both of these questions are fairly old. Is there a solution to the problem of determining whether a visitor is viewing their open tab or not?

Pretty much everything I have tried works fine in Chrome. But IE7 just fails.

I just want to set a global variable that says whether the page is being viewed.

i.e.

var isActive = true;

$(window).focus(function() {
    isActive = true;
});

$(window).blur(function() {
    isActive = false;
});

// test
setInterval(function () {
  console.log(window.isActive ? 'active' : 'inactive'); 
}, 1000);
Community
  • 1
  • 1
ComputerUser
  • 4,828
  • 15
  • 58
  • 71

2 Answers2

7

After much Googling... then some more... then some more... 4 hours or so later I finally found this link hidden in the depths of the internet. The comments suggest a small bug exists but it is fine for what I need it for.

http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

var isActive = true;
function onBlur() {
    isActive = false;
};
function onFocus(){
    isActive = true;
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}
ComputerUser
  • 4,828
  • 15
  • 58
  • 71
1

Slightly different but this was marked as the answer suggesting it worked and it is a delay that's needed. Not very elegant but if it works.

Community
  • 1
  • 1
Paul C
  • 4,687
  • 5
  • 39
  • 55
  • Maybe my question in unclear. I am not trying to open another window. I just want to halt events when the browser isn't viewing the tab. Then resume them when they return to the tab – ComputerUser Aug 08 '11 at 08:39