繁体   English   中英

使用Javascript进行用户会话管理

[英]User session management using Javascript

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

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无法访问其他标签中的数据。 那么,是否存在适用于所有选项卡的特定于浏览器的全局超时,以便在任何选项卡不空闲的情况下会话将处于活动状态? 谁能建议解决方案?

您可以使用BroadcastChannel在选项卡之间进行通信并完成此操作。 请参阅https://developer.mozilla.org/en-US/docs/Web/API/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实施后备以共享活动状态

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM