Managing user actions with jQuery

I want to write javascript that will kill sestion on a web page if the user does not take any action for some time taken from the configuration. How can I find out that the user hasn’t done anything with jQuery.

Many thanks.

+3
source share
3 answers

You can catch the mousedown and keydown events for the entire document, and then set the timeout to fire if the events are not raised within a certain period of time:

<html>
  <head>
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>

    <script type="text/javascript">
        var _idleEventId = null;
        var _idleMaxMilliSeconds = 10000;

        function OnIdle() {
            alert('You\'re idle!');
        }

        $(document).bind("mousedown keydown", function() {
            clearTimeout(_idleEventId);
            _idleEventId = setTimeout(OnIdle, _idleMaxMilliSeconds);
        });

        $(document).ready(function() {
            _idleEventId = setTimeout(OnIdle, _idleMaxMilliSeconds);
        });
    </script>
  </head>
  <body>
    Hello World
  </body>
</html>
+3
source

how to use cookies just in case: http://www.w3schools.com/JS/js_cookies.asp

then i would like it

: !

setInterval("checkForActivity()", 5000); //set a reasonable time..

function checkForActivity() {
    var user_has_moved_at = (new Date()).getTime(); //generate a time
    var time_elapsed = getCookie( COOKIE_NAME ); //get a time from previous stored
    //check how many time is passed from last move
    if ( ( user_has_moved_at - time_elapsed ) < 3600 ) { 
     //less then 1 hour.. user is still here..
        $(document.body).bind('mousemove',
        function() {
         // so update the fresh air...
            setCookie( COOKIE_NAME , user_has_moved_at);
         // unbind event
            $(document.body).unbind('mousemove');
        });

    } else {
     // more then 1 hour... destroy cookie... user is out
        setCookie(COOKIE_NAME, null); //destroy cookie
    }

};
+2

To verify that the user has not done anything, you can monitor events that mean user interaction:

var last_seen = 0;
var timeout = null;
$('body').mousemove(function () {
  last_seen = (new Date()).getTime();
  window.clearTimeout(timeout);
  timeout = window.setTimeout(clear_da_session, 10000);
});
/* ...  and likewise for things like
   $('input').focus();
   $('a').click();
   and 'keypress' events
*/

Elements clearTimeoutand setTimeouttake care of something (ie, functions clear_da_session) that occurred after some time without running any of the following events.

However, I want to emphasize once again my comment from above: do not do this at home, children! Use everything that has your server language on board. This is much more reliable than trying to track something that might not be understood.

+1
source

Source: https://habr.com/ru/post/1747013/


All Articles