我正在使用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.setItem("idleTimeValue", idleTime);
因此,如果我打开 3 个选项卡,setInterval() 函数将在所有选项卡中运行,并且 idleTime 增量为 3 秒而不是 1 秒,并且时间计算错误。
我需要在所有选项卡中显示弹出窗口,在一个选项卡中单击继续应该在所有其他选项卡中引用。
有人可以为此提出解决方案吗?请帮助伙计们
谢谢你们,我得到了解决方案。
我使用了一个本地存储值,其中存储了当前时间。如果 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;
});
您可以像下面这样调整现有实现以满足您的要求。
步骤 1:设置环境 - 创建唯一的计时器 ID 以将其与其他计时器隔离
var timerId = 'timer-'+(new Date().getTime());
localStorage.setItem(timerId, '0');
modifyAllIdleTime('0');//i.e resetting all timers
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement(){
// increament & Set only localStorage.getItem(timerId) so that it will not affect others
// Add logic to showHide
}
步骤2:修改空闲时间 - 每当需要修改其他计时器实例空闲时间时调用
function modifyAllIdleTime(idleTime) {
for(var i = 0; i < localStorage.length; i++) {
if(localStorage.key(i).indexOf('timer-') !== -1) { //if timer instance
localStorage.setItem(localStorage.key(i), idleTime);
}
}
}
第 3 步:退出 - 每当任何计时器的剩余时间为 0 时退出所有计时器
modifyAllIdleTime('600');// where 600 is the max allowed idle time in sec
deleteTimer();//call this to cleanup localStorage before navigating user to logout screen