Javascript会话超时,带有多个选项卡的弹出警报
作者:互联网
我正在使用javascript setInterval()来检查用户的空闲时间,并在自动注销之前显示弹出警报.但这不适用于多个选项卡(单个选项卡工作正常)
以下是我的代码:
localStorage.removeItem("idleTimeValue");
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
if(localStorage.getItem("idleTimeValue")) {
idleTime = parseInt(localStorage.getItem("idleTimeValue")) + 1; //increments idle time by one second
} else {
idleTime = 1;
}
localStorage.setItem("idleTimeValue", idleTime);
var timeDiff = 600;
var totTimeRemaining = timeDiff-idleTime;
if(totTimeRemaining > 0) {
$('#timeoutWindow').modal('show');
var minutes = Math.floor(totTimeRemaining / 60);
var seconds = totTimeRemaining - minutes * 60;
$('#timeoutRemainingTime').html(minutes+" minutes and "+seconds+" seconds");
} else {
window.location = httpHost+"/account/index/logout";
}
}
$(this).click(function (e)
{
localStorage.removeItem("idleTimeValue");
$('#timeoutWindow').modal('hide');
});
我在localStorage中设置空闲时间,例如-
localStorage.setItem("idleTimeValue", idleTime);
因此,如果我打开3个选项卡,则setInterval()函数将在所有选项卡中运行,idleTime也将增加3秒而不是1秒,并且时间计算错误.
我需要在所有选项卡中显示弹出窗口,然后在一个选项卡中单击“继续”应会在所有其他选项卡中显示.
有人可以为此建议解决方案吗?请大家帮忙
解决方法:
谢谢大家,我已经找到了解决方案.
我将localStorage值与当前时间一起存储在其中.如果localStorage [“ currentTime”]中不存在任何值,则将当前时间存储在localStorage中.
var currentTime = new Date();
if ( !(localStorage.getItem("currentTime")) || (localStorage.getItem("currentTime") == "") )
{
idleTime = 0;
setTimeout(function() { localStorage.setItem("currentTime", currentTime)},5000); // current time is set to localStorage after seconds (it is for setting in multiple tabs)
}
所有显示超时弹出窗口的计算都是使用localStorage.getItem(“ currentTime”)值完成的.
然后,如果用户不空闲(当用户单击某处时),则将localStorage [“ currentTime”]设置为null
$(this).click(function (e)
{
$('#timeoutWindow').modal('hide');
localStorage.setItem("currentTime", "");
idleTime = 0;
});
标签:setinterval,tabs,session-timeout,javascript,php 来源: https://codeday.me/bug/20191028/1956249.html