Click here to Skip to main content
Click here to Skip to main content
Go to top

Session Time Out Warning Message Using jQuery in ASP.NET

, 1 Sep 2014
Rate this:
Please Sign up or sign in to vote.
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.

<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 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:

 function sessLogOut()
    {
        window.location.href="/KB/aspnet/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

 <%@ 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)

Share

About the Author

Sandeep Singh Shekhawat
Software Developer Dotsquares Technology Pvt Ltd, Jaipur
India India
Currently working with ASP.NET MVC, ASP.NET Web API, SignalR, Entity Framework with Code First Approach, Knockout js and Bootstrap(css and js), Ioc using Ninject and Fluent API (Configuration and Validation)
 

Achievements

C# Corner MVP (2013 and 2014)
 

Awards

 
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 07 March 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 18 March 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 21 March 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 09 April 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 25 April 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 20 May 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 07 June 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 11 August 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 29 August 2014.
 
3rd Best C# Article of January 2014
4th Best Web Dev Article of January 2014
Follow on   Twitter

Comments and Discussions

 
QuestionWhat about browser tabs? PinmemberJake Moon2-Sep-14 17:36 
AnswerRe: What about browser tabs? PinprofessionalSandeep Singh Shekhawat2-Sep-14 18:13 
QuestionWhere is this code actually keeping the server session alive? PinmemberMember 78960972-Sep-14 8:59 
AnswerRe: Where is this code actually keeping the server session alive? PinprofessionalSandeep Singh Shekhawat2-Sep-14 15:51 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun1-Sep-14 19:33 
GeneralRe: My vote of 5 PinprofessionalSandeep Singh Shekhawat2-Sep-14 2:04 
QuestionMasterpage Pinmembercoredco7-Aug-14 8:30 
AnswerRe: Masterpage PinprofessionalSandeep Singh Shekhawat7-Aug-14 18:06 
Questionjquery plugin PinmemberdevBilal10-Feb-14 1:32 
AnswerRe: jquery plugin PinprofessionalSandeep Singh Shekhawat30-Aug-14 19:08 
QuestionMessagebox after timeout PinmemberStamps15-Jan-14 21:23 
AnswerRe: Messagebox after timeout PinprofessionalSandeep Singh Shekhawat15-Jan-14 21:45 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 1 Sep 2014
Article Copyright 2014 by Sandeep Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid