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)
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
Detect If Browser Tab Has Focus
Yes, window.onfocus
and window.onblur
should work for your scenario:
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
How to tell if browser/tab is active, and turn down volume sound when user leave
Newer browsers (IE10 and up) have support for the Page Visibility API
The Page Visibility API lets you know when a webpage is visible or in
focus. With tabbed browsing, there is a reasonable chance that any
given webpage is in the background and thus not visible to the user.
When the user minimizes the webpage or moves to another tab, the API
sends a visibilitychange event regarding the visibility of the page.
You can detect the event and perform some actions or behave
differently. For example, if your web app is playing a video, it would
pause the moment the user looks at another browser, and plays again
when the user returns to the tab. The user does not lose their place
in the video and can continue watching.
Used something like this
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
document.addEventListener(visibilityChange, handleVisibilityChange, false);
function handleVisibilityChange() {
$("video").prop('muted', document[hidden]);
}
DEMONSTRATION
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 to detect if user changes tab
You can determine if a tab or window is active by attaching a blur / focus event listener to window.
in jQuery it would be
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});
quoted from this SO answer: https://stackoverflow.com/a/1760268/680578
Determine if browser tab is active? - IE?
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;
}
Related Topics
Get Week of Year in JavaScript Like in PHP
JavaScript Implementation of Gzip
Persistent Service Worker in Chrome Extension
How to Run Multiple Npm Scripts in Parallel
How to Find the Operating System Details Using JavaScript
Performance of CSS Transitions VS. Js Animation Packages
Fullpage.Js. Adding a Scroll Delay
How to Preserve Aspect Ratio When Scaling Image Using One (Css) Dimension in IE6
JavaScript Console.Log() in an iOS Uiwebview
What Is the Standard Solution in JavaScript for Handling Big Numbers (Bignum)
How to Pass Parameters Rendered from Backend to Angular2 Bootstrap Method
Getting JavaScript Object Key List
Why Does String to Number Comparison Work in JavaScript
Change the Url in the Browser Without Loading the New Page Using JavaScript
Incrementing a Date in JavaScript
Serving Gzipped CSS and JavaScript from Amazon Cloudfront via S3