Wednesday, August 28, 2013

Session Time Out Warning Message In jQuery




In this article we will look at how to show a warning message to the user prior to 15 minutes before the session time out, in other words if the user is in an idle state for more than 5 minutes then the user gets a message in the browser.
 
What is Session?
When we work with an application on our computer, we follow some procedures, like open an application, make some changes and then close it. These procedures are much like a Session because there is an interaction between the user and computer so the computer knows who the user is. It knows everythig we do with the application. However, on the internet there is one problem: the web server doesn't know who the user is and what he does, because the web is stateless, which means a new instance of a web page class is recreated each time the page is posted on the server. In other words to say that HTTP is a stateless protocol and it doesn't hold the user/client information in a page.
Session data is stored on a per client basis; in other words for every client, the session data is stored separately. A Session provides the ability to store information in server memory and that information can be retrieved for any page.

Use jQuery
We need to add a JavaScript js file reference on the web page so we can retrieve JavaScript functions on the web page to get a message before session timeout. So we load jQuery first.
<script src="jquery/js/jquery-1.8.3.js" type="text/javascript"></script>

Variable Declaration
We need to declare some global variables; these are used to calculate the user's idle time and session time.
//How frequently to check for session expiration in milliseconds
var
sess_pollInterval = 60000;
//How many minutes the session is valid for

var
sess_expirationMinutes = 20;
//How many minutes before the warning prompt

var sess_warningMinutes = 5;
var
sess_intervalID;
var
sess_lastActivity;

Session Initialization
 

We need to create a JavaScript function that initializes the session time when the page loads. Here we use the sess_lastActivity variable to store the time the page is loaded
and after that we set the session interval.

function initSession()
{  
    sess_lastActivity = new Date();
    sessSetInterval();
    $(document).bind('keypress.session', function (ed, e)
    {
        sessKeyPressed(ed, e);
    });
}

Session Interval and Warning Message
We create two functions; one to set session interval and another to calculate session interval and to show a message whenever a session times out.

function sessSetInterval()
{
    sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
}

function
sessInterval()
{
        var now = new Date();
       
//get milliseconds of differneces
        var diff = now - sess_lastActivity;
       
//get minutes between differences
        var diffMins = (diff / 1000 / 60); 
        if (diffMins >= sess_warningMinutes)
        {
           
//wran before expiring
            //stop the timer
            sessClearInterval();
           
//promt for attention
            var active = confirm('Your session will expire in ' + (sess_expirationMinutes - sess_warningMinutes) +
                ' minutes (as of ' + now.toTimeString() + '), press OK to remain logged in ' +
                'or press Cancel to log off. \nIf you are logged off any changes will be lost.');
            if (active == true)
            {
                now = new Date(); 
              diff = now - sess_lastActivity;
                diffMins = (diff / 1000 / 60);

                if (diffMins > sess_expirationMinutes)
                {
                    sessLogOut();
                }
               
else
                {
                    initSession();
                    sessSetInterval();
                    sess_lastActivity = new Date();
                }
            }
           
else
            {
                sessLogOut();
            }
        }
    }

Logout
When the user is idle for more than 5 minutes we get an attention message from the system and whenever we click on the cancel button we move to the logout page. After 15
minutes from the time the message window was opened, we click on the OK button and then also move to the logout page. So we create a logout function, which is:

function sessLogOut()
    {
        window.location.href = 'Logout.aspx';
    }

Directory Structure
The following diagram shows the directory structure of where the web form and js files exist.
solution-explorer-in-jquery.png

Entire Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SessionInjQuery.aspx.cs" Inherits="JQueryExample.SessionInjQuery" %>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
    <title></title
>
    <script src="jquery/js/jquery-1.8.3.js" type="text/javascript"></script> 
    <script type
="text/javascript">
 
    var sess_pollInterval = 60000;
    var sess_expirationMinutes = 20;
    var sess_warningMinutes = 5;
    var sess_intervalID;
    var sess_lastActivity;

 
    function initSession()
    {  
        sess_lastActivity = new Date();
        sessSetInterval();
        $(document).bind('keypress.session', function (ed, e)
        {
            sessKeyPressed(ed, e);
        });
    }
    function sessSetInterval()
    {
        sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
    }
    function sessClearInterval()
    {
        clearInterval(sess_intervalID);
    }
    function sessKeyPressed(ed, e)
    {
        sess_lastActivity = new Date();
    }
    function sessLogOut()
    {
        window.location.href = 'Logout.aspx';
    }
    function sessInterval()   
{
        var now = new Date();
       
//get milliseconds of differneces
        var diff = now - sess_lastActivity;
       
//get minutes between differences
        var diffMins = (diff / 1000 / 60);

        if (diffMins >= sess_warningMinutes)
        {
           
//wran before expiring
           
//stop the timer
            sessClearInterval();
           
//promt for attention
            var active = confirm('Your session will expire in ' + (sess_expirationMinutes - sess_warningMinutes) +
                ' minutes (as of ' + now.toTimeString() + '), press OK to remain logged in ' +
                'or press Cancel to log off. \nIf you are logged off any changes will be lost.');
            if (active == true)
            {
                now = new Date();
                diff = now - sess_lastActivity;
                diffMins = (diff / 1000 / 60);

                if (diffMins > sess_expirationMinutes)
                {
                    sessLogOut();
                }
               
else
                {
                    initSession();
                    sessSetInterval();
                    sess_lastActivity = new Date();
                }
            }
           
else
            {
                sessLogOut();
            }
        }
    }

</script>
 
</
head>
<
body onload="initSession()">
    <form id="form1" runat
="server">
    <div
>
     <h1>Your Most Welcome!</h1
>
    </div
>
    </form
>

</
body>
</
html>

Warning Message
message-box-in-jquery.png

In the warning message we have two buttons, one is "OK" and another is a "Cancel" button. When we click the "OK" button withn 15 minutes before the warning message is shown in the browser, the session time interval will be reset but when we click on the "OK" button after 15 minutes from the warning message then we move to the logout page. Whenever we click on the "Cancel" button then we also move to the logout page.

meaasge-print-injquery.png

No comments:

Post a Comment