简体   繁体   English

使用Javascript进行用户会话管理

[英]User session management using Javascript

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. 我认为Javascript无法访问其他标签中的数据。 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? 谁能建议解决方案?

You can use BroadcastChannel to communicate between the tabs and get this done. 您可以使用BroadcastChannel在选项卡之间进行通信并完成此操作。 Refer https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel 请参阅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 但请记住,较旧的浏览器不支持broadcastChannel,因此请查看支持表,并在需要时使用localStorage实施后备以共享活动状态

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

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