Click here to Skip to main content
15,884,473 members
Articles / Web Development / HTML
Tip/Trick

Session Expiration Time out Popup using jquery

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
10 Mar 2017CPOL1 min read 122.2K   4.9K   15   26
 In this article, I will tell you how to create a cross-browser session expiration popup box using jQuery easily

Introduction

In this article, I will tell you how to create a cross-browser session expiration popup box using jQuery easily

Background

Session timeout is very much important in every project. There are so many articles already written for session timeout. Therefore, in this article I will tell you how to create use session timeout using jQuery easily. We can configure session timeout and after finishing this timing, user will receive notification like that, you need to logout to extend timeout.

Using the code

Part 1: Creating a Popup using Bootstrap

To show session timeout popup we need two popups, one for showing session expire warning like “Your session    will expire in -- seconds. Do you want to extend the session?” It will give three options

  1. OK to extend
  2. Cancel to close popup
  3. Logout Now to Logout

Please find below screenshot for it

Image 1

Second one is session expired message. This will redirect to logout page

Image 2

Below is bootstrap UI of these 2 popups

HTML
<!--Start Show Session Expire Warning Popup here -->

    <div class="modal fade" id="session-expire-warning-modal" aria-hidden="true" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

        <div class="modal-dialog" role="document">

            <div class="modal-content">

                <div class="modal-header">                 

                    <h4 class="modal-title">Session Expire Warning</h4>

                </div>

                <div class="modal-body">

                    Your session will expire in <span id="seconds-timer"></span> seconds. Do you want to extend the session?

                </div>

                <div class="modal-footer">

                    <button id="btnOk" type="button" class="btn btn-default" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4px;  background-color: #428bca; color: #FFF;">Ok</button>

                    <button id="btnSessionExpiredCancelled" type="button" class="btn btn-default" data-dismiss="modal" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4px; background-color: #428bca; color: #FFF;">Cancel</button>

                    <button id="btnLogoutNow" type="button" class="btn btn-default" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4px;  background-color: #428bca; color: #FFF;">Logout now</button>

                </div>

            </div>

        </div>

    </div>

    <!--End Show Session Expire Warning Popup here -->

    <!--Start Show Session Expire Popup here -->

    <div class="modal fade" id="session-expired-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

        <div class="modal-dialog" role="document">

            <div class="modal-content">

                <div class="modal-header">

                    <h4 class="modal-title">Session Expired</h4>

                </div>

                <div class="modal-body">

                    Your session is expired.

                </div>

                <div class="modal-footer">

                    <button id="btnExpiredOk" onclick="sessionExpiredRedirect()" type="button" class="btn btn-primary" data-dismiss="modal" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4px; background-color: #428bca; color: #FFF;">Ok</button>

                </div>

            </div>

        </div>

    </div>

Part B: JavaScript Code

  1. Setting Server Ping Configuration:

This configuration will always ping server to check session Alive or not

var sessServerAliveTime = 10 * 60 * 200;
  1. Setting session timeout configuration

Here you can give configuration for session timeout

var sessionTimeout = 19 * 60000;
  1. Use of Local Storage

Here we used localstorage for setting sessionSlide variable.

  1. Use of sessPingServer() Method

Here we used sessPingServer Method for Ping to sever using Ajax Call. In code snippet, I commented my ajax pinging code.

Code Snippet

JavaScript
var sessServerAliveTime = 10 * 60 * 2;
var sessionTimeout = 1 * 60000;
var sessLastActivity;
var idleTimer, remainingTimer;
var isTimout = false;

var sess_intervalID, idleIntervalID;
var sess_lastActivity;
var timer;
var isIdleTimerOn = false;
localStorage.setItem('sessionSlide', 'isStarted');

function sessPingServer() {
    if (!isTimout) {
        //$.ajax({
        //    url: '/Admin/SessionTimeout',
        //    dataType: "json",
        //    async: false,
        //    type: "POST"
        //});

        return true;
    }
}

function sessServerAlive() {
    sess_intervalID = setInterval('sessPingServer()', sessServerAliveTime);
}

function initSessionMonitor() {
    $(document).bind('keypress.session', function (ed, e) {
        sessKeyPressed(ed, e);
    });
    $(document).bind('mousedown keydown', function (ed, e) {

        sessKeyPressed(ed, e);
    });
    sessServerAlive();
    startIdleTime();
}

$(window).scroll(function (e) {
    localStorage.setItem('sessionSlide', 'isStarted');
    startIdleTime();
});

function sessKeyPressed(ed, e) {
    var target = ed ? ed.target : window.event.srcElement;
    var sessionTarget = $(target).parents("#session-expire-warning-modal").length;

    if (sessionTarget != null && sessionTarget != undefined) {
        if (ed.target.id != "btnSessionExpiredCancelled" && ed.target.id != "btnSessionModal" && ed.currentTarget.activeElement.id != "session-expire-warning-modal" && ed.target.id != "btnExpiredOk"
             && ed.currentTarget.activeElement.className != "modal fade modal-overflow in" && ed.currentTarget.activeElement.className != 'modal-header'
    && sessionTarget != 1 && ed.target.id != "session-expire-warning-modal") {
            localStorage.setItem('sessionSlide', 'isStarted');
            startIdleTime();
        }
    }
}

function startIdleTime() {
    stopIdleTime();
    localStorage.setItem("sessIdleTimeCounter", $.now());
    idleIntervalID = setInterval('checkIdleTimeout()', 1000);
    isIdleTimerOn = false;
}

var sessionExpired = document.getElementById("session-expired-modal");
function sessionExpiredClicked(evt) {
    window.location = "Logout.html";
}

sessionExpired.addEventListener("click", sessionExpiredClicked, false);
function stopIdleTime() {
    clearInterval(idleIntervalID);
    clearInterval(remainingTimer);
}

function checkIdleTimeout() {
     // $('#sessionValue').val() * 60000;
    var idleTime = (parseInt(localStorage.getItem('sessIdleTimeCounter')) + (sessionTimeout)); 
    if ($.now() > idleTime + 60000) {
        $("#session-expire-warning-modal").modal('hide');
        $("#session-expired-modal").modal('show');
        clearInterval(sess_intervalID);
        clearInterval(idleIntervalID);

        $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 100);
        $("#session-expired-modal").css('z-index', 2000);
        $('#btnExpiredOk').css('background-color', '#428bca');
        $('#btnExpiredOk').css('color', '#fff');

        isTimout = true;

        sessLogOut();

    }
    else if ($.now() > idleTime) {
        ////var isDialogOpen = $("#session-expire-warning-modal").is(":visible");
        if (!isIdleTimerOn) {
            ////alert('Reached idle');
            localStorage.setItem('sessionSlide', false);
            countdownDisplay();

            $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 500);
            $('#session-expire-warning-modal').css('z-index', 1500);
            $('#btnOk').css('background-color', '#428bca');
            $('#btnOk').css('color', '#fff');
            $('#btnSessionExpiredCancelled').css('background-color', '#428bca');
            $('#btnSessionExpiredCancelled').css('color', '#fff');
            $('#btnLogoutNow').css('background-color', '#428bca');
            $('#btnLogoutNow').css('color', '#fff');

            $("#seconds-timer").empty();
            $("#session-expire-warning-modal").modal('show');

            isIdleTimerOn = true;
        }
    }
}

$("#btnSessionExpiredCancelled").click(function () {
    $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) - 500);
});

$("#btnOk").click(function () {
    $("#session-expire-warning-modal").modal('hide');
    $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) - 500);
    startIdleTime();
    clearInterval(remainingTimer);
    localStorage.setItem('sessionSlide', 'isStarted');
});

$("#btnLogoutNow").click(function () {
    localStorage.setItem('sessionSlide', 'loggedOut');
    window.location = "Logout.html";
    sessLogOut();
    $("#session-expired-modal").modal('hide');

});
$('#session-expired-modal').on('shown.bs.modal', function () {
    $("#session-expire-warning-modal").modal('hide');
    $(this).before($('.modal-backdrop'));
    $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

$("#session-expired-modal").on("hidden.bs.modal", function () {
    window.location = "Logout.html";
});
$('#session-expire-warning-modal').on('shown.bs.modal', function () {
    $("#session-expire-warning-modal").modal('show');
    $(this).before($('.modal-backdrop'));
    $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

function countdownDisplay() {

    var dialogDisplaySeconds = 60;

    remainingTimer = setInterval(function () {
        if (localStorage.getItem('sessionSlide') == "isStarted") {
            $("#session-expire-warning-modal").modal('hide');
            startIdleTime();
            clearInterval(remainingTimer);
        }
        else if (localStorage.getItem('sessionSlide') == "loggedOut") {         
            $("#session-expire-warning-modal").modal('hide');
            $("#session-expired-modal").modal('show');
        }
        else {

            $('#seconds-timer').html(dialogDisplaySeconds);
            dialogDisplaySeconds -= 1;
        }
    }
    , 1000);
};

function sessLogOut() {
   // $.ajax({
   //     url: 'Logout.html',
   //     dataType: "json",
  //      async: false,
  //      type: "POST"
 //   });
    
    window.location = "Logout.html";
}

Please find attached code for demo .SessionTimeout.zip Image 3  I already set One Minute wait timer for popup. After 1 minute it will show timeout confirmation message and after that session expire popup will show

Happy Programming!!

Don’t forget to leave your feedback and comments below!

License

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


Written By
Technical Lead
India India
Sujit Bhujbal is Senior Software Engineer having over 12 + years of Experience in .NET core , C#, Angular , SQL Server and has worked on various platforms. He worked during various phases of SDLC such as Requirements and Analysis, Design and Construction, development, maintenance, Testing, UAT.

He is Microsoft Certified Technology Specialist (MCTS) in Asp.net /WCF Applications. He worked at various levels and currently working as a Senior Software Engineer.

His core areas of skill are Web application development using WPF,WCF , C#.Net, ASP.Net 3.5, WCF, SQL Server 2008, CSS, Java script Web design using HTML, AJAX and Crystal Reports

He is proficient in developing applications using SilverLight irrespective of the language, with sound knowledge of Microsoft Expression Blend and exposure to other Microsoft Expression studio tools.


Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

------------------------------------------------------------------------
Blog: Visit Sujit Bhujbal

CodeProject:- Sujit Bhujbal codeproject

DotNetHeaven:- DotNetHeaven

CsharpCorner:-CsharpCorner

Linkedin :-Linkedin

Stack-Exchange: <a href="http://stackexchange.com/users/469811/sujit-bhu

Comments and Discussions

 
Questionsecond dialog Pin
Wafaa Hakamy20-Jun-21 5:19
Wafaa Hakamy20-Jun-21 5:19 
Questionextending time Pin
Wafaa Hakamy20-Jun-21 5:34
Wafaa Hakamy20-Jun-21 5:34 
QuestionChange timeout length Pin
Member 1505653026-Jan-21 5:39
Member 1505653026-Jan-21 5:39 
QuestionAwesome, Sujeet! Pin
RationalRabbit23-Feb-20 21:01
RationalRabbit23-Feb-20 21:01 
QuestionNice work! CSS Question... Pin
Member 1463036422-Oct-19 2:58
Member 1463036422-Oct-19 2:58 
AnswerRe: Nice work! CSS Question... Pin
RationalRabbit23-Feb-20 20:56
RationalRabbit23-Feb-20 20:56 
QuestionDoes this work with PHP session? Pin
Member 1412341319-Jan-19 9:51
Member 1412341319-Jan-19 9:51 
QuestionLogging out even after clicking Yes to continue the session. Pin
Vineet Prabhu30-Aug-18 23:08
Vineet Prabhu30-Aug-18 23:08 
AnswerRe: Logging out even after clicking Yes to continue the session. Pin
Vineet Prabhu4-Sep-18 20:04
Vineet Prabhu4-Sep-18 20:04 
AnswerRe: Logging out even after clicking Yes to continue the session. Pin
Member 79086063-Oct-18 11:57
Member 79086063-Oct-18 11:57 
GeneralRe: Logging out even after clicking Yes to continue the session. Pin
RationalRabbit26-Feb-20 20:03
RationalRabbit26-Feb-20 20:03 
GeneralRe: Logging out even after clicking Yes to continue the session. Pin
Member 1490040328-Jul-20 2:07
Member 1490040328-Jul-20 2:07 
GeneralRe: Logging out even after clicking Yes to continue the session. Pin
Sujeet Bhujbal24-Aug-20 22:19
Sujeet Bhujbal24-Aug-20 22:19 
QuestionThank you Pin
Khaled_Rachico15-Dec-17 3:41
Khaled_Rachico15-Dec-17 3:41 
QuestionWhy is it that the popup warning message only appears in pages with partial view only but not in normal view pages? Pin
Member 1277091527-Nov-17 14:12
Member 1277091527-Nov-17 14:12 
PraiseNice work! Pin
Member 1277091522-Nov-17 22:18
Member 1277091522-Nov-17 22:18 
QuestionIt's not working for me Pin
Member 135125129-Nov-17 5:14
Member 135125129-Nov-17 5:14 
Questioncode not working Pin
mukeshkane13-Mar-17 21:54
professionalmukeshkane13-Mar-17 21:54 
AnswerRe: code not working Pin
Sujeet Bhujbal14-Mar-17 2:42
Sujeet Bhujbal14-Mar-17 2:42 
GeneralRe: code not working Pin
Sujeet Bhujbal14-Mar-17 2:59
Sujeet Bhujbal14-Mar-17 2:59 
GeneralRe: code not working Pin
mukeshkane14-Mar-17 3:36
professionalmukeshkane14-Mar-17 3:36 
GeneralRe: code not working Pin
Sujeet Bhujbal15-Mar-17 22:11
Sujeet Bhujbal15-Mar-17 22:11 
QuestionDownload Link Broken Pin
thund3rstruck12-Mar-17 6:21
thund3rstruck12-Mar-17 6:21 
AnswerRe: Download Link Broken Pin
Sujeet Bhujbal12-Mar-17 20:37
Sujeet Bhujbal12-Mar-17 20:37 
GeneralMy vote of 5 Pin
Carsten V2.010-Mar-17 22:57
Carsten V2.010-Mar-17 22:57 

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.