正如你所说,你需要检查对话框打开之前的时间。当页面加载时,您可以假设完整的1800秒。
我想你可能想要类似这样的东西(请参阅下面的代码和注释中的注释)。
$(function() {
var timer;
var closeDialogAfter = 180; //The default counter value
var idleTimeOutLimit = <?php echo $sessionTimeoutValue ?>; //Time after which
var signOutScript = '/index.php?action=logout'; //logout url
var keepAliveScript = '/ajax/handler-keep-me-alive.php'; //php page to handle ajax request to keep the session alive
var getSessionTimeScript = '/ajax/get_session_time.php'; //php page to handle ajax request for the remaining session length
var $dialogCountdown = $('#dialog-countdown'); //the container used to display the counter
var $idleTimeout = $('#idleTimeout'); //the div that is used for the dialog
function startTimeoutCounter(t) {
t = Math.max(closeDialogAfter, parseInt(t, 10) || 0);
$idleTimeout.dialog("close");
setTimeout(getSessionTimeRemaining, (t - closeDialogAfter) * 1000);
}
function updateTimeoutCounter() {
if($idleTimeout.dialog("isOpen")) {
setTimeout(function() {
timer = timer - 1;
$dialogCountdown.text(timer);
if(timer < 2) {
// Here, forceLogOut() can't be assumed because
// the session may have been kept alive from another tab.
// Therefore, call getSessionTimeRemaining().
getSessionTimeRemaining();
} else {
updateTimeoutCounter();
}
}, 1000);
} else {
$dialogCountdown.text(closeDialogAfter);
}
}
function forceLogOut() {
$idleTimeout.dialog("close");
window.location = signOutScript;
}
function getSessionTimeRemaining() {
$.get(getSessionTimeScript).then(function(t) {
t = parseInt(t, 10) || 0;
if(t <= 0) {
forceLogOut();
} else if(t <= closeDialogAfter) {
timer = closeDialogAfter;
$dialogCountdown.text(timer);
$idleTimeout.dialog("open");
} else {
startTimeoutCounter(t);
}
}, function(error) {
// Something went wrong, safest action is logout
// This will only happen under abnormal circumstances
console.error(error);
forceLogOut();
});
};
function keepAlive() {
$.get(keepAliveScript).then(startTimeoutCounter);
}
$idleTimeout.dialog({
resizable: false,
autoOpen: false,
width: 400,
open: updateTimeoutCounter,
buttons: {
"Yes, Keep working": keepAlive,
"No, End Session": forceLogOut
}
});
// On page load, the session should have been reset by the script that serves this page,
// therefore no need to call keepAlive(), though that would do the same job.
startTimeoutCounter(idleTimeOutLimit);
});
你会看到主要的结构差异是$(function() {...})现在包装一切。这避免了使用全局名称空间的需要。
新功能getSessionTimeRemaining()及其服务器端对应getSessionTimeScript是允许多个选项卡响应会话超时的核心。
两个脚本keepAliveScript和getSessionTimeScript(可以是具有不同查询字符串的相同脚本)都必须以秒为单位返回时间t。 t被认为是一个字符串,它被转换为数字parseInt()。您可能希望返回稍微少于实际会话时间的时间,从而允许短暂的“宽限期”。你不想要的是给用户希望在会话已经过期时保持会话。
功能startTimeoutCounter(t)现在接受秒的时间,以便它可以在任何时间保持,这并不一定是完整的1800秒,所以根据呼叫是否来自keepAlive()或getSessionTimeRemaining()(异步)工作。
新功能keepAlive()允许整理“按钮”的定义。
全部完全未经测试。你可能仍然需要修补它。