2

I am trying to fire out the user when idle, using javascript across tabs, the below code working fine for single tab for multiple tab it is not working properly

For Eg: I have set 10 secs as idle time and left the first tab it throws out the user on 10 seconds, assume i opened the first tab at 00:00:05 hours and opened second tab at 00:00:10 hours and working on second tab for 00:00:13 hours and left both the tabs the project have to logout on 00:00:23 right? but it logs out on 00:00:15, I don't know whats happening right here, if it was not refreshing properly how could it stay on second tab for a long time when i am using it? if it is refreshing properly how could it log me out based on first opened tab, and the code as follows.

<script>
var IDLE_TIMEOUT = 10; //seconds
localStorage.setItem("setTimeOut", "0");

document.onclick = function () {    
    localStorage.setItem("setTimeOut", "0");
};

document.onmousemove = function () {   
    localStorage.setItem("setTimeOut", "0");
};

document.onkeypress = function () {  
    localStorage.setItem("setTimeOut", "0");
};

document.onfocus = function () {  
    localStorage.setItem("setTimeOut", "0");
};


window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {  
    localStorage.setItem("setTimeOut", parseInt(localStorage.getItem("setTimeOut"))+1);
    if (localStorage.getItem("setTimeOut") >= IDLE_TIMEOUT) {
        alert('Times up!, You are idle for about 15 minutes, Please login to continue');
        document.location.href = "logout.php";
    }
}
</script>
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

This line will run every second for each instance of your app (tab). That means that if you have 2 tabs open, then its incrementing by 2 every second instead of 1.

localStorage.setItem("setTimeOut", parseInt(localStorage.getItem("setTimeOut"))+1);

You can fix this by using a specific time when the user will be logged out, rather than a countdown.

Steve Land
  • 4,852
  • 2
  • 17
  • 36
1

Instead of incrementing the value each second on each tab, which means every second it will be increased with the number of tabs open rather than 1 second, simply set the current time on interaction and then compare to that every second.

So, in your event handlers, do this instead:

localStorage.setItem("lastInteraction", Date.now())

... and then in your CheckIdleTime() function, remove the localStorage.setItem() and change your if condition to this:

Number(localStorage.getItem("lastInteraction")) + (IDLE_TIMEOUT * 1000) < Date.now()

The condition takes the time when the last interaction occurred, adds the timeout constant and then checks if the current time (now) has passed that value.

Lennholm
  • 7,205
  • 1
  • 21
  • 30