Detect when browser tab / window is active
Is it possible to detect when browser window is active / inactive
I tried:
$(window).on('focus', function(){
console.log(1);
});
$(window).on('blur', function(){
console.log(2);
});
But it seems that it only works when the user clicks on the window. but showing 2 when the user clicks eg. browser address bar.
What I want to achieve is to detect when the active tab is active.
How can this code be improved?
+3
source to share
1 answer
Active means the tab is visible. But if you want to know if the user's mouse is right on the page, you can use this:
<html onmouseenter="document.getElementById('h1').innerHTML = 'active'"onmouseleave="document.getElementById('h1').innerHTML = 'not active'">
<body style="width:100%;height:100px">
<h1 id="h1">not active</h1>
</body>
</html>
With the simple code above, you can determine if the user mouse is on the page or not.
EDIT: using the page visibility API:
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";
}
function handleVisibilityChange() {
if (document[hidden]) {
//Not visible, Do whatever
}
else {
//Visible
}
}
if (typeof document.addEventListener === "undefined" ||
typeof document[hidden] === "undefined") {
alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
}
else {
document.addEventListener(visibilityChange, handleVisibilityChange, false);
+2
source to share