1

is there any way how to find out if my page is being used now? I mean, if is it on the user screen. tab with page is active on the screen. I have some server-client data flow and i want to optimize it. I want to have data flowing just if user is watching page, not when page is open in browser but hidden in non-active tab. Does anybody know? Thank you.

Mito86
  • 13
  • 5

1 Answers1

2

If you want to see if the tab is currently visible (not a hidden tab), then you can use the visibility API.

Here's an example of a small function letting you on most browsers both register for visibility change events and check the visibility :

//  var visible = vis(); // gives the current state
//  vis(function(){ ... });   // register a visibility change event handler
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];
        }
})();

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758