Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if browser tab is active? - IE?

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);
like image 401
JasonS Avatar asked Aug 08 '11 08:08

JasonS


People also ask

How do you check if a browser tab is currently active or not?

The Page Visibility API: It lets the developers know if the current tab is currently active or not. When the user switches to another tab or minimizes the window, then the pagevisibilitychange event gets triggered. This API added these properties to the document object. document.

How can we detect when user closes browser?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

How can I tell if my Windows is active?

To find out, select the Start button, and then select Settings > Update & Security > Activation . You'll be able to confirm that your Windows 10 has been activated and that your Microsoft account is associated with your digital license.

How do I check my browser focus?

Use the visibilitychange event to detect if a browser tab has focus or not, e.g. document. addEventListener('visibilitychange', checkTabFocused) . The event is fired at the document when the contents of its tab have become visible or have been hidden.


1 Answers

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;
}
like image 114
JasonS Avatar answered Sep 29 '22 06:09

JasonS