Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when browser tab/window is active [duplicate]

Is It possible to detect when browser window Is active/inactive

I did try:

$(window).on('focus', function(){
    console.log(1);
});
$(window).on('blur', function(){    
    console.log(2);    
});

But it seems that it's working only when user will click the window. but showing 2 when user will click eg. browser address bar.

What I want to achieve is to detect when current tab is active one.

How to improve this code?

like image 348
LJ Wadowski Avatar asked Oct 19 '25 23:10

LJ Wadowski


1 Answers

Active means when the tab is visible. But if you want to tell if the user's mouse is directly on the page, you could 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 tell if the users 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);
like image 101
DividedByZero Avatar answered Oct 21 '25 13:10

DividedByZero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!