我的应用程序中有一个会话计时器,用于检查用户是否在特定时间内处于空闲状态。以下是我的代码。
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无法访问其他选项卡中的数据。那么是否存在适用于所有选项卡的浏览器特定的全局超时,以便在任何选项卡不空闲时会话将处于活动状态?有人可以建议解决方案吗?
答案 0 :(得分: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)
}
因此,每次选项卡中都有活动时,它会通知所有其他选项卡,因此他们也会更新计时器。
但请记住,旧版浏览器不支持broadcastChannel,因此请查看支持表,如果需要,请使用localStorage实现回退以共享活动状态