Greytree

TamWiki

For a mouse who is a packrat

Technology » Inactivity Timeout On A Page
How to implement an inactivity timeout on a web page

Summary:this is what goes at the top of the site

(redirected from Main.InactivityTimeoutOnAPage)

On this page... (hide)

Using Java Script, one can construct a set of timers to schedule an inactivity timeout. Inactivity is indicated by the lack of keyboard and mouse button presses. If there is a way to indicate mouse movement, that would be useful, as well. We'll be using jQuery, so look out for that, and remember to include the jQuery javascript in your code.


Example 1

First, assuming we are using PHP, we can set a couple of configuration variables:

  1. // Number of milliseconds to wait before timing out the page due to inactivity
  2.  $page_timeout = 1000 * 60 * 30; // 30 minutes
  3.  $page_timeout_warning_timeout = 1000 * 30; // 30 seconds

Next, in the code that emits the header:

  1. <?php if ($page_timeout > 0) { ?>
  2.         var autoCloseTimer;
  3.         var timeoutObject;
  4.         var timePeriod = <?php echo $page_timeout ?>;
  5.         var warnPeriod = <?php echo $page_timeout_warning_timeout ?>;
  6.  
  7.         function promptForClose()
  8.         {
  9.         $('#autoCloseDiv').css('display','block');
  10.          autoCloseTimer = setTimeout("definitelyClose()",warnPeriod);
  11.         }
  12.  
  13.  
  14.         function autoClose()
  15.         {
  16.                 //alert("auto close prompt");
  17.          $('#autoCloseDiv').css('display','block');
  18.          autoCloseTimer = setTimeout("definitelyClose()",timePeriod); //starts countdown to closure
  19.         }
  20.  
  21.         function cancelClose()
  22.         {
  23.  
  24.          clearTimeout(autoCloseTimer); //stops auto-close timer
  25.          $('#autoCloseDiv').css('display','none'); //hides message
  26.         //alert("canceled close");
  27.         }
  28.  
  29.         function resetTimeout()
  30.         {
  31.                 //alert("timer reset");
  32.           clearTimeout(timeoutObject); //stops timer
  33.           timeoutObject = setTimeout("promptForClose()",timePeriod); //restarts timer from 0
  34.         }
  35.  
  36.  
  37.         function definitelyClose() {
  38.                 //alert("logging off")
  39.             location.href="logoff.php"; // for example, log the user off if inactive
  40.         }
  41.  <?php } // close if ($page_timeout) ?>

Next, we need to set the <body> tags appropriately:

  1. <body onLoad ="timeoutObject=setTimeout('promptForClose()',timePeriod);"<?php
  2.                 // only set the triggers if a user is logged in
  3.                 if ($page_timeout > 0): ?>
  4.                 onkeydown='resetTimeout();' onmousedown='resetTimeout();'
  5.                 <?php endif: ?>>

Finally, we create a <div> in the <body> of the document to serve as our pop-up indicator that the session is closing:

  1. <div id='autoCloseDiv' style="display:none;">
  2.                 <h3><?php echo get_vocab('inactivitywarning') ?></h3>
  3.                 <p><?php echo get_vocab('warningmessage') ?></p>
  4.                 <div class="submit_buttons">
  5.                 <input type='button' value='<?php echo get_vocab('closebutton') ?>' onclick='definitelyClose();' />
  6.                 <input type='button' value='<?php echo get_vocab('cancelbutton') ?>' onclick='cancelClose();' />
  7.                 </div>
  8.         </div>

Note use of language substitution function get_vocab(). This is done with PHPLocalization?.

In addition, the following CSS is useful for displaying the autoCloseDiv:

  1. #autoCloseDiv {
  2.          background-color: #FFF;
  3.         color: #000
  4.         margin-left: -100px;
  5.         margin-top: -100px;
  6.         width: 200px;
  7.         height: 200px;
  8.         position: absolute;
  9.         top: 50%;
  10.         left: 50%;
  11.         text-align: center;
  12.         border: 1px solid #999;
  13.  }

Edit: Turns out there is a mouse movement event handler. jQuery example of such is shown at jQuery mousemove handler. So for the above example, adding the following should suffice:

  1. <script>
  2.     $("body").mousemove(resetTimeout());
  3.   </script>

Example 2

This is a more complete jQuery UI example. Here, I've recast the functions as anonymous functions assigned to variables, so they can be used in assignments to the jQuery callbacks. Also, not that everything that is needed by the code inside the $(document).ready function must reside within that function's scope. If you access something outside that scope, the jQuery UI functions will fail, and you'll get very odd results. Also, there is additional code below that will reset the timeout functions once in the logged-off state.

  1. <script type="text/javascript" charset="utf-8">
  2.  /* <![CDATA[ */
  3.  $(function(){
  4.         var autoCloseTimer;
  5.         var timeoutObject;
  6.         var timePeriod = 5 * 1000;  // n * 1000 - number of seconds until timeout
  7.         var warnPeriod = 5 * 1000; // n * 1000 - number of seconds to show warning before timing out
  8.  
  9.         var promptForClose = function()
  10.         {
  11.                 $('#autoCloseDiv').dialog('open');
  12.                 autoCloseTimer = setTimeout(definitelyClose,warnPeriod);
  13.         }
  14.  
  15.         var cancelClose = function()
  16.         {
  17.                 $('#autoCloseDiv').dialog('close'); //hides message
  18.                 clearTimeout(autoCloseTimer); //stops auto-close timer
  19.                 resetTimeout();
  20.         }
  21.  
  22.         var  resetTimeout = function()
  23.         {
  24.                 clearTimeout(timeoutObject); //stops timer
  25.                 if (timePeriod > 0) {
  26.                         timeoutObject = setTimeout(promptForClose,timePeriod); //restarts timer from 0
  27.                 }
  28.         }
  29.  
  30.  
  31.         var definitelyClose = function() {
  32.                 clearTimeout(autoCloseTimer);
  33.                 $('#autoCloseDiv').dialog('close');
  34.                 timePeriod = 0;
  35.                 $("#junk-text").hide('slow');
  36.                 $("#logged-off").show('slow');
  37.         }
  38.  
  39.         $("#logged-off").hide();
  40.         $("#logged-off").text("Logged off - click to reset");
  41.         $("#logged-off").addClass('ui-state-highlight');
  42.         $("#logged-off").addClass('ui-corner-all');
  43.         $("#logged-off").css({'width' : '100px', 'text-align' : 'center'});
  44.         $("#logged-off").attr('title','click to reset');
  45.         $("#logged-off").click(function(){
  46.                 timePeriod = 5 * 1000;
  47.                 resetTimeout();
  48.                 $(this).hide('slide');
  49.                 $("#junk-text").show('slow');
  50.                 return false; // prevent anything else from happenning
  51.         });
  52.  
  53.         $('#inactivitytimeout').click(resetTimeout);
  54.         $('#inactivitytimeout').keypress(resetTimeout);
  55.         $('#topnav a:first-child').focus(); // must provide a focus on the body for something to accept a keydown event
  56.  
  57.         resetTimeout();
  58.         var warnSeconds = warnPeriod / 1000;
  59.         $("#warn-seconds").text(warnSeconds);
  60.         $("#autoCloseDiv").dialog({
  61.                 autoOpen: false,
  62.                 buttons: {
  63.                         'Log off' : definitelyClose,
  64.                         'Continue' : cancelClose
  65.                 }
  66.         });
  67.  
  68.  })
  69.  
  70.  /* ]]> */
  71.  </script>

The page body would have:

  1. <body id="inactivitytimeout" title="inactivitytimeout" lang="en-US">
  2.         <div id="autoCloseDiv" title="Warning!" style="display: block">
  3.                 <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
  4.                 Session will close in <span id="warn-seconds"></span> seconds.
  5.         </div>
  6.  
  7.  <div id="topnav"><a href="#"></a></div>
  8.  <div id="content">
  9.  <p id="junk-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sem dui, laoreet ut scelerisque quis, dictum vitae nisi. Nulla facilisi. Nunc a turpis sed lectus hendrerit pulvinar at vel sapien. Vivamus placerat auctor iaculis. Nam gravida gravida felis, in viverra eros vehicula at. Praesent vulputate blandit lectus, ut scelerisque erat laoreet auctor. Maecenas blandit pharetra nisl, sit amet pretium lorem congue non. Praesent dignissim, lectus nec tristique lobortis, felis metus placerat risus, id fermentum lectus nisl id mauris. Nullam viverra accumsan massa eget congue. Nam neque lacus, tempus vel fringilla eget, molestie dapibus diam. Proin sapien est, luctus vitae congue eget, ultricies a enim. </p>
  10.  <p id="logged-off"></p>
  11.  </div>


Tags: Categories: HowTos

Recent Changes | Printable View | Page History | Edit Page
Page last modified on April 17, 2012, at 08:59 PM by ImportText?