Code With Mark
Home
About
Resources
Contact

jquery session timeout

Learn how to easily add session timeout with jquery plugin

Below is the  session timeout jquery plugin

(function ($) {
    $.jq_easy_session_timeout = function (userSettings) {

        
        // GLOBAL VARIABLES
        

        let defaultSettings = {
            activityEvents: 'click keypress scroll wheel mousewheel mousemove',
            applicationId: 'easy_session_time_out',
            dialogMessage: 'Your session is about to expire due to inactivity.',
            dialogTimeRemainingLabel: 'Time remaining',
            dialogTitle: 'Session Expiration Warning',
            documentTitle: null,
            heartbeatCallback: null,
            heartbeatUrl: window.location.href,
            heartRate: 30,
            inactivityLogoutUrl: 'https://www.codewithmark.com',
            inactivityDialogDuration: 15,
            localStoragePrefix: null,
            logoutNowButtonText: 'Logout Now',
            manualLogoutUrl: null,
            maxInactivitySeconds: 600,
            stayLoggedInButtonText: 'Stay Logged In'
        };

        let settings = $.extend({}, defaultSettings, userSettings);

        // Set some fallback settings

        settings.documentTitle = settings.documentTitle || settings.dialogTitle;
        settings.localStoragePrefix = settings.localStoragePrefix || settings.applicationId;
        settings.manualLogoutUrl = settings.manualLogoutUrl || settings.inactivityLogoutUrl;

        let sessionStartTime;
        let heartbeatTimer;
        let inactivityTimer;
        let originalPageTitle = document.title;
        let localStorage = {};

        
        // HEARTBEAT
        

        
        let heartbeat = function (heartbeat_url) {
            $.get(heartbeat_url, function(data, textStatus, jqXHR) {
                if ($.isFunction(settings.heartbeatCallback)) {
                    settings.heartbeatCallback(data, textStatus, jqXHR);
                }
            });
        }

        
        let startHeartbeatTimer = function () {
            heartbeatTimer = setInterval(
                function () {
                    heartbeat(settings.heartbeatUrl);
                },
                (settings.heartRate * 1000)
            );
        }

        
        let stopHeartbeatTimer = function () {
            clearInterval(heartbeatTimer);
        }

        
        // CHECK INACTIVITY
        

        
        let checkInactivity = function () {
            let loggedOutStatus = getLoggedOutStatus();
            let sessionStartTime = getSessionStartTime();

            // Check that we were able to retrieve the logged out status and session
            // start time from local storage.

            if (typeof loggedOutStatus === 'boolean' && typeof sessionStartTime === 'number') {

                // If we have already been logged out elsewhere, logout here;
                // otherwise, calculate and handle inactivity.

                if (loggedOutStatus) {
                    logout();
                } else {
                    let elapsedSeconds = Math.floor(((new Date()).getTime() - sessionStartTime) / 1000);
                    let remainingSeconds = (settings.maxInactivitySeconds - elapsedSeconds);
                    let secondsLabel = (remainingSeconds == 1) ? 'second' : 'seconds';

                    $('#jquery-idle-hands-time-remaining').text(
                        remainingSeconds + ' ' + secondsLabel
                    );

                    

                    if (elapsedSeconds > settings.maxInactivitySeconds) {
                        logout(settings.inactivityLogoutUrl);
                    } else if (remainingSeconds <= settings.inactivityDialogDuration) {
                        $(document).off(settings.activityEvents, activityHandler);

                        showDialog();
                    } else {
                        hideDialog();
                    }
                }
            }
        }

        
        let startInactivityTimer = function () {
            setSessionStartTime((new Date()).getTime());

            inactivityTimer = setInterval(checkInactivity, 1000);
        };

        
        let stopInactivityTimer = function () {
            clearInterval(inactivityTimer);
        }

        
        let restartInactivityTimer = function () {
            stopInactivityTimer();
            startInactivityTimer();
        }

        
        let activityHandler = function (event) {
            restartInactivityTimer();
        }

        
        // LOCAL STORAGE
        

        
        let initializeLocalStorage = function () {
            let config = {
                namespace: settings.localStoragePrefix,
                keyDelimiter: '.'
            };   

            localStorage.basil = new window.Basil(config);

            // Clear any previously set values

            flushLocalStorage();
        }

         
        localStorage.set = function (key, value) {
            localStorage.basil.set(key, value);
        }

        
        localStorage.get = function (key) {
            return localStorage.basil.get(key);
        }

        
        localStorage.flush = function () {
            localStorage.basil.reset();
        }

        
        let setSessionStartTime = function (time) {
            localStorage.set('sessionStartTime', time);

            sessionStartTime = time;
        }

        
        let getSessionStartTime = function () {
            return localStorage.get('sessionStartTime');
        }

        
        let setLogoutUrl = function (logoutUrl) {
            localStorage.set('logoutUrl', logoutUrl);
        }

        
        let getLogoutUrl = function () {
            return localStorage.get('logoutUrl');
        }

         
        let flushLocalStorage = function () {
            localStorage.flush();
        }

        
        let setLoggedOutStatus = function (loggedOutStatus) {
            localStorage.set('loggedOutStatus', loggedOutStatus);
        }

        
        let getLoggedOutStatus = function () {
            return localStorage.get('loggedOutStatus');
        }

        
        // DIALOG
        

        
        let createDialog = function () {
            let dialogContainer = '<div id="jquery-idle-hands">' +
                                  '<div id="jquery-idle-hands-overlay"></div>' +
                                  '<div id="jquery-idle-hands-dialog">' +
                                  '<div id="jquery-idle-hands-dialog-title">' + settings.dialogTitle + '</div>' +
                                  '<div id="jquery-idle-hands-message-container">' +
                                  '<p id="jquery-idle-hands-message">' + settings.dialogMessage + '</p>' +
                                  '<p id="jquery-idle-hands-time-remaining-label">' + (settings.dialogTimeRemainingLabel + ': ') +
                                  '<span id="jquery-idle-hands-time-remaining"></span>' +
                                  '</p>' +
                                  '</div>' +
                                  '<hr/>' +
                                  '<div id="jquery-idle-hands-button-container">' +
                                  '<button id="jquery-idle-hands-stay-logged-in-button">' + settings.stayLoggedInButtonText + '</button>' +
                                  '<button id="jquery-idle-hands-logout-button">' + settings.logoutNowButtonText + '</button>' +
                                  '</div>' +
                                  '</div>' +
                                  '</div>';

            $('body').append(dialogContainer);

            // Stay Logged In button

            $('#jquery-idle-hands-stay-logged-in-button').on('click', function (event) {
                event.stopPropagation();

                stayLoggedIn();
            });

            // Logout button

            $('#jquery-idle-hands-logout-button').on('click', function (event) {
                event.stopPropagation();

                logout(settings.manualLogoutUrl);
            });
        }

        
        let showDialog = function () {
            document.title = settings.documentTitle;

            $('#jquery-idle-hands').show(function () {
                //$('#jquery-idle-hands button').first().focus();
            });
        }

        
        let hideDialog = function () {
            document.title = originalPageTitle;

            $('#jquery-idle-hands').hide();
        }

        
        let logout = function (logoutUrl) {
            if (logoutUrl) {
                setLogoutUrl(logoutUrl);
            } else {
                logoutUrl = getLogoutUrl();
            }

            // Check that we have a logout URL in case there was a problem getting
            // it from local storage, then redirect.

            if (logoutUrl) 
            {
                setLoggedOutStatus(true);

                stopHeartbeatTimer();
                stopInactivityTimer();

                $('#jquery-idle-hands-dialog').hide();

                if (typeof logoutUrl == 'function')
                {
                    logoutUrl('logoutUrl');
                }
                else
                {
                    window.location = logoutUrl;
                }
            }
        }

        
        let stayLoggedIn = function () {
            flushLocalStorage();

            setLoggedOutStatus(false);

            restartInactivityTimer();

            $(document).on(settings.activityEvents, activityHandler);

            hideDialog();
        }
        
        let css = function(){

            var s1 ="#jquery-idle-hands{display:none;margin:0!important;padding:0!important;font-family:Roboto,Verdana,sans-serif!important;line-height:1.5!important;color:#333}#jquery-idle-hands-overlay{position:fixed!important;width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;b1ackground-color:rgba(0,0,0,.25)!important;background-color:rgb(0 0 0 / 82%)!important;z-index:1001!important;margin:0!important;margin:0!important}#jquery-idle-hands-dialog{position:absolute!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;z-index:1002!important;background-color:#fff!important;border-radius:4px!important;padding:4px!important;margin:0!important;min-width:300px!important;border:1px solid #000;font-family:Roboto,Verdana,sans-serif!important;line-height:1.5!important;color:#333}#jquery-idle-hands-dialog-title{color:#fff!important;text-align:center!important;background-color:red!important;border-radius:4px!important;padding:4px!important;margin:4px!important;text-align:center!important;line-height:1.5!important;font-family:Roboto,Verdana,sans-serif!important;font-size:16px}#jquery-idle-hands-message-container p{padding:0!important;margin:14px!important;text-align:left!important;line-height:1.5!important;font-family:Roboto,Verdana,sans-serif!important;color:#333;font-size:14px}#jquery-idle-hands hr{padding:0!important;margin:0 0 4px 0!important;border:1px solid silver!important;border-bottom:none!important;font-family:Roboto,Verdana,sans-serif!important;color:#333;line-height:1.5!important;height:1px!important}#jquery-idle-hands-button-container{text-align:center!important;margin:0!important;padding:0!important;font-family:Roboto,Verdana,sans-serif!important;color:#333;line-height:1.5!important}#jquery-idle-hands-button-container button{width:40%!important;padding:5px 0!important;font-size:14px;margin:5px 10px!important;line-height:1.5!important;font-family:Roboto,Verdana,sans-serif!important;color:#333}#jquery-idle-hands-stay-logged-in-button{background-color:green!important;color:#fff!important}";
            var str = ''
            +'<div class="easy_session_logout">'
                +'<style>'
                    + s1
                +'</style>'
            +'</div>';
            $(str).appendTo('body');
        }


        
        // START IDLE HANDS
        

        
        let initialize = function () {
            
            css();

            initializeLocalStorage();

            setLoggedOutStatus(false);

            $(document).on(settings.activityEvents, activityHandler);

            createDialog();

            startHeartbeatTimer();
            startInactivityTimer();
        }



        
        $(document).ready(function($) 
        {
           $.getScript('https://cdnjs.cloudflare.com/ajax/libs/basil.js/0.4.10/basil.min.js', function(d) 
            {
                initialize();
            });
        });
    };
}(jQuery));

Here is the whole html code with session timeout js file included:

<!DOCTYPE html>
<html>
<head>
	 
	<title> jQuery Easy Session Timeout Plugin - Code With Mark </title>

	<meta name="viewport" content="width=device-width, initial-scale=1">

	<meta name="description" content="This ">

	<meta name="author" content="Code With Mark">
	<meta name="authorUrl" content="http://codewithmark.com">
 
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">


	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script> 
	 

	<script src="jquery_easy_session_timeout.js"></script> 



	<script type="text/javascript">
	$(document).ready(function($) 
	{

		function start_timer () 
		{
		
		$.jq_easy_session_timeout(
	 	{	    
	 		inactivityDialogDuration: 5, 
		    maxInactivitySeconds: 10,	     
		    inactivityLogoutUrl1:'https://google.com',
		    inactivityLogoutUrl:function () 
		    {
		    	//log user off
		    	console.log('log out code goes here');

		    },
		});
		}

		$(document).on('click', '.btn_start_timer', function(event) 
		{
			event.preventDefault();
			start_timer();
		});

	});
	</script>

</head>
<body>

<div class="container" style="padding-top:25px;">

	<div class="text-center">
    	<h1 class="text-center">jQuery Easy Session Timeout Plugin</h1>
    	
    </div>

    <hr>
    <p>
    	Shows the warning dialog after 5 seconds. <br><br>
    	If user takes no action (interacts with the page in any way), browser is redirected to redirUrl. <br><br>
    	On any user action (mouse, keyboard or touch) the timeout timer is reset. 
    </p>

    <div class="text-center">
    	<span class="btn btn-success btn_start_timer">Start Timer - Code With Mark</span>
    </div>
    

</div>

</body>
</html>
For Web Developers

Stop Building Websites That Pay You Once.

Use Shiply CMS to launch websites faster, manage clients easier, and turn every project into recurring monthly income.

Start Building Faster 🚀 Download Shiply CMS
Javascript Cookies Vs Local StorageJavascript Cookies Vs Local Storage←Previous
Create PHP Secure Cookie Login SystemCreate PHP Secure Cookie Login SystemNext→

Related Posts

  • How Google Developers Think (And Why You Should Too)
  • Add Google Sign-In in 2 Minutes
  • Form Validation in 1 Line

Top Posts Viewed

Using JavaScript Window Onload Event Correctly
66 views
How Google Developers Think (And Why You Should Too)
56 views
Learn To Create YouTube Video Downloader
55 views

Categories

Courses
Excel
Google Script
Javascript
jQuery
Microsoft Access
MongoDB
Node JS
PHP
Quick Tip
Uncategorized
Wordpress