How to detect when a tab is focused or not in Chrome with Javascript?
2015 update: The new HTML5 way with visibility API (taken from Blowsie's comment):
document.addEventListener('visibilitychange', function(){
document.title = document.hidden; // change tab text for demo
})
The code the original poster gives (in the question) now works, as of 2011:
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
edit: As of a few months later in Chrome 14, this will still work, but the user must have interacted with the page by clicking anywhere in the window at least once. Merely scrolling and such is insufficient to make this work. Doing window.focus()
does not make this work automatically either. If anyone knows of a workaround, please mention. 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
Detect which tab/window is being focused in Google Chrome
Don't know a content script only solution, but this can be easily done with help of background page:
content_script.js:
function task() {
chrome.extension.sendRequest("is_selected", function(isSelected) {
if(isSelected) {
//this tab in focus
} else {
//not in focus
}
});
}
setInterval(task, 5000);
background.html:chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request == "is_selected") {
chrome.tabs.getSelected(null, function(tab){
if(tab.id == sender.tab.id) {
sendResponse(true); //in focus (selected)
} else {
sendResponse(false); //not in focus
}
});
}
});
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 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]
(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
. 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 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.
Related Topics
What's the API Key for in Google Maps API V3
How to Filter an Array in JavaScript
JavaScript .Replace Only Replaces First Match
How to Sign into Google with Selenium Automation Because of "This Browser or App May Not Be Secure."
Javascript: Uploading a File... Without a File
Load Local JSON File into Variable
Converting a Buffer into a Readablestream in Node.Js
Counting Frequency of Characters in a String Using JavaScript
Get Unique Results from JSON Array Using Jquery
How to Sort an Associative Array by Its Values in JavaScript
How to Load All Files in a Directory Using Webpack Without Require Statements
How to Convert Numbers Between Different Bases in JavaScript
Adding New Data to Firebase Users
JavaScript Call Nested Function