Javascript session timeout with popup alert for multiple tabs
Asked Answered
C

2

4

I am using javascript setInterval() to check user idle time and show a popup alert before automatic logout. But it does not work for multiple tabs (working fine for single tab)

Following is my code :

localStorage.removeItem("idleTimeValue");
var idleInterval    = setInterval(timerIncrement, 1000);


function timerIncrement()  
{
    if(localStorage.getItem("idleTimeValue")) {
        idleTime            = parseInt(localStorage.getItem("idleTimeValue")) + 1; //increments idle time by one second
    } else {
        idleTime            = 1;
    }

    localStorage.setItem("idleTimeValue", idleTime);

    var timeDiff            = 600; 
    var totTimeRemaining    = timeDiff-idleTime;


    if(totTimeRemaining > 0) {

                $('#timeoutWindow').modal('show');
                var minutes = Math.floor(totTimeRemaining / 60);
                var seconds = totTimeRemaining - minutes * 60;
                $('#timeoutRemainingTime').html(minutes+" minutes and "+seconds+" seconds");
    } else {
                window.location = httpHost+"/account/index/logout";
    }

}


$(this).click(function (e) 
{
    localStorage.removeItem("idleTimeValue");
    $('#timeoutWindow').modal('hide');
});

I am setting the idle time in localStorage like -

localStorage.setItem("idleTimeValue", idleTime);

So if I open 3 tabs, setInterval() function will run in all tabs, also idleTime increments by 3 seconds instead of 1 second and time calculations is happening wrongly.

I need to show popup in all tabs and clicking continue in one tab should reflct in all other tabs.

Can anybody suggest a solution for this? Please help guys

Courcy answered 18/11, 2014 at 11:45 Comment(3)
phpobserver.wordpress.com/2014/02/02/…Yeager
What you could do is also store a value which refers to if the counter is in use or not. Then you can check while opening the second and third tab if you need to increase the timer or not.Brawn
Thank you Pols. I will try like this..!Courcy
C
5

Thank you guys, I got the solution for this.

I used a localStorage value with current time stored in it. If there is no value exists in localStorage["currentTime"], stored current time in localStorage .

var currentTime         = new Date();

if ( !(localStorage.getItem("currentTime")) || (localStorage.getItem("currentTime") == "") )
{
        idleTime        = 0;
        setTimeout(function() { localStorage.setItem("currentTime", currentTime)},5000); // current time is set to localStorage after  seconds (it is for setting in multiple tabs)
} 

All calculations to show timeout popup is done using localStorage.getItem("currentTime") value.

Then I set localStorage["currentTime"] to null if user is not idle (when user clicks somewhere)

$(this).click(function (e) 
{
    $('#timeoutWindow').modal('hide');
    localStorage.setItem("currentTime", "");
    idleTime = 0;
});
Courcy answered 20/11, 2014 at 10:1 Comment(1)
But I suspect, your solution works, You sets 5-sec timeout, how will you restrict to logout?Bearish
T
1

You can tweak your existing implementation like below to fullfill your requirement.

Step 1: Setup environment - Creating unique timer Id to isolate it from other timers

var timerId = 'timer-'+(new Date().getTime());
localStorage.setItem(timerId, '0');
modifyAllIdleTime('0');//i.e resetting all timers

var idleInterval    = setInterval(timerIncrement, 1000);

function timerIncrement(){
    // increament & Set only localStorage.getItem(timerId) so that it will not affect others
    // Add logic to showHide
}

Step 2: Modifying Idle Time - call whenever other timer instance idle time need to be modified

function modifyAllIdleTime(idleTime) {
    for(var i = 0; i < localStorage.length; i++) {
        if(localStorage.key(i).indexOf('timer-') !== -1) { //if timer instance
            localStorage.setItem(localStorage.key(i), idleTime);
        }
    }
}

Step 3: Exit - exit all timer whenever remaining time comes to 0 for any of the timer

modifyAllIdleTime('600');// where 600 is the max allowed idle time in sec
deleteTimer();//call this to cleanup localStorage before navigating user to logout screen
Tacmahack answered 19/11, 2014 at 5:13 Comment(2)
Thanks Amitesh. But if I use sessionStorage, the value will be lost if I close the tab right? Also it is not working in new window.Courcy
@Courcy you are right. I misinterpreted it because of its name :) sessionStorage persist to single tab/window and is not shared across tabs. I have modified answer to use localStorage where we need to cleanup the timer before logout in case of timer expire.Tacmahack

© 2022 - 2024 — McMap. All rights reserved.