How to Detect Browser Window is Active or not

  1150 views   7 months ago Javascript

Javascript is great programming language to learn. You can do many funny things with Javascript. In the web browser, you can dynamically change in the HTML dom elements.

In this article, we will go through on how to check if user is active or inactive. For that we will check if is there any browser event inserted like mousemove, click event or scroll event.

There are many usage where user activity is required to check. Mostly this is useful to logout user after inactive or popup modal to confirm user.

Using Javascript

Bellow is the function on how to check user if user is active or inactive using Javascript. On these events trigger, resetTime() function will trigger and time will be cleared. So if none of these event happen, then alertUser() function will be trigger.

You can set any action in alertUser() method, that you want to do.

<script type="text/javascript">
    function inactivityTime() {
        var time;
        
        // events
        window.onload = resetTime;
        window.onclick = resetTime;
        window.onkeypress = resetTime;
        window.ontouchstart = resetTime;
        window.onmousemove = resetTime;
        window.onmousedown = resetTime;
        window.addEventListener('scroll', resetTime, true);

        function alertUser() {
            // do your task here
            alert("User is inactive.");
        }

        function resetTime() {
            clearTimeout(time);
            time = setTimeout(alertUser, 1000 * 10); // 10 seconds
        }

    };

    // run the function
    inactivityTime(); 
</script>

Using JQuery

Same thing you can do with JQuery. Bellow code is how you can do this with JQuery.

<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var inactiveTime;
        $('*').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {

            function alertUser() {
                // do your task here
                alert("User is inactive.");
            }
            
            clearTimeout(inactiveTime);

            inactiveTime = setTimeout(alertUser, 1000 * 10); // 10 seconds
        });
        $("body").trigger("mousemove");
    });
</script>

After the defined time, if there is no event trigger, then alertUser() function calls, you can do your task in this function.

I hope you liked this article,

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]