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

Leave a Comment