How to Detect If a Browser Window Is Not Currently Active

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

Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API (on MDN) now allows us to more accurately detect when a page is hidden to the user.

document.addEventListener("visibilitychange", onchange);

Current browser support:

  • Chrome 13+
  • Internet Explorer 10+
  • Firefox 10+
  • Opera 12.10+ [read notes]

The following code falls back to the less reliable blur/focus method in incompatible browsers:

(function() {
var hidden = "hidden";

// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;

function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};

evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}

// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});
})();

onfocusin and onfocusout are required for IE 9 and lower, while all others make use of onfocus and onblur, except for iOS, which uses onpageshow and onpagehide.

Javascript - Detect if window is inactive but still visible

You can't. I looked into this for a project a while back and active vs inactive is the only distinction the browser can make.

Information about the positions of other windows on the system isn't passed to the browser, especially given that this route could possibly be reverse engineered to expose a security risk. It's much safer to keep each window in the dark about what other programmes on the system are doing.

You can gather information based on events happening in the current window - for example detecting the opening of a print dialogue - but not from other windows.

The Page Visibility API has 95% coverage and is probably the closest you can come - but you already know this, because it's the top answer in each question you linked. You're out of luck here.

How do I detect if the browser window is active

The reason it doesn't work is that you're calling the functions immediately and assigning the return value of undefined to onfocus and onblur.

Instead, onfocus and onblur should reference the functions by name.

Try this:

window.onfocus = focuswindow;
window.onblur = hidewindow;

Notice that I removed the () call operators. Now onfocus and onblur are referencing the functions, and will call them when the events occur.

Detect if browser tab is active or user has switched away

Now we can use the visibility API.

To deal with the different browser-specific syntaxes, I made this small code :

var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();

Usage :

var visible = vis(); // gives current state

vis(aFunction); // registers a handler for visibility changes

Example :

vis(function(){
document.title = vis() ? 'Visible' : 'Not visible';
});

Demonstration page

How to tell if browser/tab is active

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)

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

The above code is working fine in Safari v3.0.4 (WebKit 530+), the bug has been resolved it seems. I've checked it in Google Chrome v3.0.195.27 and it has the same Safari bug, although it has a newer version of WebKit.

Active window detection

You could use window.onfocus and window.onblur for this instead of that wall of code. It is supported by all the main browsers and works perfectly fine for the purpose you want. It detects when you change tabs, for example, or open another application as you said.

Example:

window.onfocus = function() {
console.log('Focused');
};

window.onblur = function() {
console.log('Not focused');
};

Is there a way to tell if a browser is active?

You can use the Page Visibility API for this.

It is compatible with IE 10+.

Small example of code:

document.addEventListener("visibilitychange", function(e) {

console.log("visibility changed!", e);

if (document.visibilityState === 'visible') {

console.info("window is visible now!");

}

else {

console.info("something else, maybe you changed tab or minimized window!");

}

console.log("check the visibilityState property on document object for more info");

});


Related Topics



Leave a reply



Submit