【问题标题】:User session management using Javascript使用 Javascript 进行用户会话管理
【发布时间】:2018-08-07 21:41:17
【问题描述】:

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

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 无法访问其他选项卡中的数据。那么是否有任何特定于浏览器的全局超时适用于所有选项卡,以便在任何选项卡不空闲时会话将处于活动状态?任何人都可以提出解决方案吗?

【问题讨论】:

    标签: javascript session timeout settimeout


    【解决方案1】:

    您可以使用 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)
    }
    

    所以每次选项卡中有活动时,它都会通知所有其他选项卡,因此它们也会更新计时器。

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

    【讨论】:

    • 感谢您提供此解决方案,但并非所有浏览器都支持此 BroadcastChannel,尤其是 IE。我正在寻找一些所有浏览器都支持的解决方案。让我试试 localStorage
    猜你喜欢
    • 2011-06-10
    • 2016-02-07
    • 2012-12-15
    • 2013-12-18
    • 1970-01-01
    • 2016-04-26
    • 2014-09-21
    • 2017-01-23
    相关资源
    最近更新 更多