Reputation: 3782
I have one session timer in my application which checks if the user is idle for a specific time. Below is my code.
var sessionTimeout;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
// I have some more dom events here
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(sessionTimeout);
sessionTimeout = setTimeout(logout, 30000)
}
If the user opens two tabs simultaneously and keeps the one tab idle and other not, he will be logged out after the timeout period because the timer will run in the other tab which is not in focus. Is there any way to handle this? I think Javascript can't access the data in the other tabs. So is there any global timeouts specific to the browser which applies to all tabs so that the session will be active if any tab is not idle? Can anyone suggest solutions?
Upvotes: 0
Views: 1926
Reputation: 3845
You can use BroadcastChannel to communicate between the tabs and get this done. Refer https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
A possible solution pseudo code can look like
var sessionTimeout;
var bc = new BroadcastChannel('session_channel');
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
bc.onmessage = resetTimer;
// I have some more dom events here
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
bc.postMessage('activity');
clearTimeout(sessionTimeout);
sessionTimeout = setTimeout(logout, 30000)
}
So every time there is activity in the tab, it will notify all the other tabs, so they update the timer as well.
But do keep in mind that broadcastChannel is not supported in older browsers, so look at the support table and if needed implement fallback using localStorage to share the activity state
Upvotes: 2