javascriptevents

How to determine if a user is actually looking at a web page?


Is it possible to determine whether a user is active on the current web page or, say, focused on a different tab or window?

It seems that if you switch tabs, any JavaScript set on a timeout/interval continues running. It would be nice to be able to 'pause' the events when the user is not on the page.

Would something like attaching a mouseover event to the body work, or would that be too resource-intensive?


Solution

  • You can place onfocus/onblur events on the window.

    There's wide support for those events on the window.

    Example:

    window.onfocus = function() {
        document.body.innerHTML += "<br>I've gained focus.";
    };
    
    window.onblur = function() {
        document.body.innerHTML += "<br>I've lost focus.";
    };
    span {color:blue}
    <span>CLICK IN AND OUT OF THIS FRAME.
        <br><br>(It has its own "window" object).</span>
    <br><br>