Detect if browser tab is active or user has switched away

How can I detect if a user is switching to another browser tab?

Currently, I have this:

$(window).on("blur focus", function (e) {

    var prevType = $(this).data("prevType");

    if (prevType != e.type) { //  reduce double fire issues
        switch (e.type) {
            case "blur":
                $('.message').html('<div class="alert alert-error">Oops. You navigated away from the ads <a id="start" class="butt green">Resume</a></div>');

                var myDiv = $("#bar");
                myDiv.clearQueue();
                myDiv.stop();
                clearInterval($timer);
                $timer = null;
                break;
            case "focus":
                // do work
                break;
        }
    }

    $(this).data("prevType", e.type);
});

But that only works when the user is minimizing the active window.


Solution 1:

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

Solution 2:

These 3 lines of code worked for me

document.addEventListener("visibilitychange", function() {
      document.title = document.hidden ? "I'm away" : "I'm here";
});
      

reference link: document.hidden

demo: https://iamsahilralkar.github.io/document-hidden-demo/