Reputation: 4878
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);
Upvotes: 5
Views: 6847
Reputation: 4878
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;
}
Upvotes: 7
Reputation: 4776
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.
Upvotes: 1