Automatic Logout After 15 Minutes Of Inactivity in JavaScript

Automatic Logout After 15 Minutes Of Inactivity in JavaScript
Code Snippet:Session Timeout
Author: Carey Hinoki
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 875
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a functionality to automatic logout after 15 minutes of inactivity on a webpage. It ensures enhanced security by automatically logging out users after given idle time. Using a debounce function and event listeners, it monitors user activity, resetting the session timeout accordingly.

The script also creates a notification bar, alerting users about the impending logout due to inactivity. Users can extend their session by clicking a link in the notification. Implementing this code enhances website security by proactively managing user sessions.

How to Automatic Logout After 15 Minutes Of Inactivity in JavaScript

1. Include the necessary HTML structure for your web application. Ensure your HTML file contains the required elements.

<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <link rel="stylesheet" href="styles.css"> <!-- Link to your CSS file -->
 <title>Your Web App</title>
 </head>
 <body>
 <!-- Your web app content goes here -->
 <script src="script.js"></script> <!-- Link to your JavaScript file -->
 </body>
 </html>

2. Copy the following CSS code into your styles.css file. This styling is essential for creating the session timeout notification bar.

.session-timeout-notification
{ 
   width: 100%;
    background-color: #BADA55;
    border-bottom: 1px solid #000;
    color: #c01065;
    display: none;
    padding: 4px;
    position: fixed;
    top: 0;
    left: 0;
}

3. Copy the following JavaScript code into your script.js file. This code includes a debounce function and the SessionTimeout module to handle session timeouts and user interactions.

function debounce(func, threshold) {
    var timeout;

    return function() {
        var context = this,
            args = arguments;

        if (timeout) {
            clearTimeout(timeout);
        }

        timeout = setTimeout(function() {
            func.apply(context, args);

            timeout = null;
        }, threshold || 250);
    };
}

var SessionTimeout = (function() {
    var session_duration = 10,
        session_timeout_id,
        logout_duration = 15, //15 minutes
        session_timeout_duration = (session_duration - logout_duration) * 1000,
        logout_id,
        logout_timeout_duration = logout_duration * 1000,
        events = 'keydown mousedown',
        notification_element;

    return {
        init: function() {
            var that = this;

            document.addEventListener(events.split(' ')[0], debounce(function () {
                that.handler.apply(that);
            }, 500));
            
            this.startIdleTimeout();
        },

        handler: function() {                    
            // reset session timeout
            clearTimeout(session_timeout_id);

            this.startIdleTimeout();
        },
      
        startIdleTimeout: function () {
            var that = this;

            session_timeout_id = setTimeout(function () {
                that.idle.apply(that); 
            }, session_timeout_duration);
        },

        idle: function() {
            // create bar
            notification_element = this.createTimeoutNotification();

            // display bar
            notification_element.style.display = 'block';

            // remove events
            document.removeEventListener('keydown', this.handler);
            document.removeEventListener('mousedown', this.handler);

            // start logout timeout
            this.startLogoutTimeout();
            
            // start logout countdown
            this.startLogoutCountdown();

            // add logout events
            this.attachTimeoutNotificationEvents();
        },

        createTimeoutNotification: function() {
            var notification_element = document.createElement('div');
            notification_element.className = 'session-timeout-notification';
            notification_element.innerHTML = [
                '<strong>Hey!</strong> you will be logged off in <strong class="time">' + logout_duration + '</strong> seconds due to inactivity. ',
                '<a href="#">Click here to continue using www.example.com</a>'
            ].join('');
            
            document.body.appendChild(notification_element);

            return notification_element;
        },

        removeTimeoutNotification: function() {
            notification_element.style.display = 'none';
            document.body.removeChild(notification_element);
        },

        attachTimeoutNotificationEvents: function() {
            var that = this,
                dismiss_element = notification_element.querySelector('a');

            dismiss_element.addEventListener('click', function() {
                // reset timer to prevent logout
                clearTimeout(logout_id);

                that.removeTimeoutNotification();

                that.init();
            });
        },

        startLogoutTimeout: function() {
            var that = this;

            logout_id = setTimeout(function() {
                alert('REDIRECT:LOGOUT');
                
                that.removeTimeoutNotification.apply(that);
            }, logout_timeout_duration);
        },

        startLogoutCountdown: function(time) {
            var that = this,
                time = time || logout_duration - 1;

            setTimeout(function() {
                notification_element.querySelector('.time').innerHTML = time;

                time--;

                if (time > 0) {
                    that.startLogoutCountdown.call(that, time);
                }
            }, 1000);
        }
    };
}());

SessionTimeout.init();

Adjust the session_duration and logout_duration variables in the SessionTimeout module according to your application’s requirements. These variables represent the total session duration and the time until automatic logout, respectively.

That’s all! hopefully, you have successfully created functionality to automatically logout after a given time of inactivity on a webpage. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X