Javascript session timeout with popup alert for multiple tabs

空扰寡人 提交于 2019-12-01 08:18:06

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;
});

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!