Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

Session Time Out Warning Message Using jQuery in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.95/5 (26 votes)
1 Sep 2014CPOL3 min read 123.4K   3.4K   66   20
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

Introduction

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 everything 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.

Procedure to Create Session Time Out Warning Message Using jQuery 

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.

HTML
<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.

HTML
//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.  

HTML
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.

HTML
 function sessSetInterval()
{
    sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
}
function sessInterval()
{
        var now = new Date();
        //get milliseconds of differences
        var diff = now - sess_lastActivity;
        //get minutes between differences

        var diffMins = (diff / 1000 / 60); 
        if (diffMins >= sess_warningMinutes)
        {
            //warn before expiring

            //stop the timer
            sessClearInterval();
            //prompt 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:

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

Using the Code

Directory Structure

The following diagram shows the directory structure of where the web form and js files exist.

Directory Structure

Figure 1.1 Directory structure for application

Entire Code

HTML
 <%@ 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) {
                //warn before expiring
                //stop the timer
                sessClearInterval();
                //prompt 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

Warning message in jQuery

Figure 1.2 Warning Message

In the warning message, we have two buttons, one is "OK" and another is a "Cancel" button. When we click the "OK" button within 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.

Logout from Application

Figure 1.3 Session Expire 
 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
He is awarded for Microsoft TechNet Guru, CodeProject MVP and C# Corner MVP. http://l-knowtech.com/

Comments and Discussions

 
Questionpop up issue Pin
Mohamed Yasin1-Nov-15 23:17
Mohamed Yasin1-Nov-15 23:17 
QuestionThis program will not extend the session Pin
Ptmujeeb9121-Sep-15 18:12
Ptmujeeb9121-Sep-15 18:12 
GeneralMy vote of 5 Pin
sudipta sham5-Feb-15 21:18
sudipta sham5-Feb-15 21:18 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat6-Feb-15 17:16
professionalSandeep Singh Shekhawat6-Feb-15 17:16 
QuestionChanged interval not working on all computers Pin
Maxx Cairn23-Jan-15 6:03
Maxx Cairn23-Jan-15 6:03 
QuestionNeed Help Pin
nuwB12-Dec-14 10:40
nuwB12-Dec-14 10:40 
QuestionWhat about browser tabs? Pin
Jake Moon2-Sep-14 17:36
Jake Moon2-Sep-14 17:36 
AnswerRe: What about browser tabs? Pin
Sandeep Singh Shekhawat2-Sep-14 18:13
professionalSandeep Singh Shekhawat2-Sep-14 18:13 
GeneralRe: What about browser tabs? Pin
Ozair Kafray14-Apr-15 2:20
Ozair Kafray14-Apr-15 2:20 
GeneralRe: What about browser tabs? Pin
Member 104738511-Aug-17 19:01
professionalMember 104738511-Aug-17 19:01 
QuestionWhere is this code actually keeping the server session alive? Pin
Member 78960972-Sep-14 8:59
Member 78960972-Sep-14 8:59 
AnswerRe: Where is this code actually keeping the server session alive? Pin
Sandeep Singh Shekhawat2-Sep-14 15:51
professionalSandeep Singh Shekhawat2-Sep-14 15:51 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun1-Sep-14 19:33
Humayun Kabir Mamun1-Sep-14 19:33 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat2-Sep-14 2:04
professionalSandeep Singh Shekhawat2-Sep-14 2:04 
QuestionMasterpage Pin
coredco7-Aug-14 8:30
coredco7-Aug-14 8:30 
AnswerRe: Masterpage Pin
Sandeep Singh Shekhawat7-Aug-14 18:06
professionalSandeep Singh Shekhawat7-Aug-14 18:06 
Questionjquery plugin Pin
EngrBS10-Feb-14 1:32
professionalEngrBS10-Feb-14 1:32 
here is Jquery plugin..simple to use.
8. Implementation of user session expiry after 5 idle Seconds[^]
BILAL SOHAIL

AnswerRe: jquery plugin Pin
Sandeep Singh Shekhawat30-Aug-14 19:08
professionalSandeep Singh Shekhawat30-Aug-14 19:08 
QuestionMessagebox after timeout Pin
Stamps15-Jan-14 21:23
Stamps15-Jan-14 21:23 
AnswerRe: Messagebox after timeout Pin
Sandeep Singh Shekhawat15-Jan-14 21:45
professionalSandeep Singh Shekhawat15-Jan-14 21:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.