Javascript session timeout with popup alert for multiple tabs

前端 未结 2 1157
予麋鹿
予麋鹿 2021-01-14 08:40

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 t

2条回答
  •  孤城傲影
    2021-01-14 09:12

    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
    

提交回复
热议问题