使用Javascript进行用户会话管理

使用Javascript进行用户会话管理,javascript,session,timeout,settimeout,Javascript,Session,Timeout,Settimeout,我的应用程序中有一个会话计时器,用于检查用户是否在特定时间空闲。下面是我的代码 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

我的应用程序中有一个会话计时器,用于检查用户是否在特定时间空闲。下面是我的代码

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

如果用户同时打开两个选项卡,并且其中一个选项卡处于空闲状态,而另一个选项卡处于非空闲状态,则在超时时间后,他将注销,因为计时器将在另一个未聚焦的选项卡中运行。有什么办法处理这个问题吗?我认为Javascript无法访问其他选项卡中的数据。那么,是否存在适用于所有选项卡的特定于浏览器的全局超时,以便在任何选项卡未空闲时会话将处于活动状态?有人能提出解决方案吗?

您可以使用广播频道在选项卡之间进行通信并完成此操作。提及

一个可能的解决方案是伪代码

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)
}
因此,每次选项卡中有活动时,它都会通知所有其他选项卡,因此它们也会更新计时器


但是请记住,旧浏览器不支持broadcastChannel,因此请查看支持表,如果需要,请使用localStorage实现回退以共享活动状态。您可以使用broadcastChannel在选项卡之间通信,并完成此操作。提及

一个可能的解决方案是伪代码

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)
}
因此,每次选项卡中有活动时,它都会通知所有其他选项卡,因此它们也会更新计时器


但请记住,旧浏览器不支持broadcastChannel,因此请查看支持表,如果需要,使用localStorage实现回退以共享活动状态

感谢此解决方案,但并非所有浏览器都支持此广播频道,尤其是IE。我正在寻找一些在所有浏览器中都支持的解决方案。让我尝试一下LocalStorageThank这个解决方案,但并非所有浏览器都支持这个广播频道,尤其是IE。我正在寻找一些所有浏览器都支持的解决方案。让我试试本地存储