如果用户没有发出请求,也没有移动鼠标或键盘或触摸设备等,那么从应用程序的角度来看,即使他们的眼球没有,用户也是“空闲的”。
如果用户正在滚动,您可以使用 javascript 来监听滚动事件(onscroll
例如,通过 ),但这不是 100% 可靠的,因为 (1) 依赖于 javascript,并且 (2) 如果您正在查看简短的文章或使用高/大幅面显示器(例如可以旋转 90 度的显示器)。
也许您可以用不同的方式处理这个问题:使用 cookie、单点登录或类似技术来预先验证或自动验证请求,以便用户的会话可以安全地终止并重新启动,而无需用户手动登录。
您可以处理此问题的另一种方法是维护一个“ping”进程,该进程定期 ping 服务器(setInterval()
例如,通过 )以保持会话处于活动状态,并使用单独的超时(可能类似于 ASP.NET 的“身份验证超时”)使用)来跟踪何时应该注销“空闲”用户。然后用户操作,如滚动、请求页面、聚焦字段、移动鼠标等,可以执行“ping 重置”,将空闲计数器重置为 0。
示例/概念 - 作为练习留给读者完善它:
var idleTime = 0; // how long user is idle
var idleTimeout = 1000 * 60 * 20; // logout if user is idle for 20 mins
var pingFrequency = 1000 * 60; // ping every 60 seconds
var warningTime = 1000 * 60 * 2; // warning at 2 mins left
var warningVisible = false; // whether user has been warned
setInterval(SendPing, pingFrequency);
setInterval(IdleCounter, 1000); // fire every second
function IdleCounter() {
idleTime += 1000; // update idleTime (possible logic flaws here; untested example)
if (console) console.log("Idle time incremented. Now = " + idleTime.toString());
}
function SendPing() {
if (idleTime < idleTimeout) {
// keep pinging
var pingUrl = "tools/keepSessionAlive.php?idleTime=" + idleTime;
$.ajax({
url: pingUrl,
success: function () {
if (console) console.log("Ping response received");
},
error: function () {
if (console) console.log("Ping response error");
}
});
// if 2 mins left, could show a warning with "Keep me on" button
if ((idleTime <= (idleTimeout - (idleTimeout - warningTime))) && !warningVisible) {
ShowTimeoutWarning();
}
} else {
// user idle too long, kick 'em out!
if (console) console.log("Idle timeout reached, logging user out..");
alert("You will be logged off now dude");
window.location.href = "logoff.aspx"; // redirect to "bye" page that kills session
}
}
function ShowTimeoutWarning() {
// use jQuery UI dialog or something fun for the warning
// when user clicks OK set warningVisible = false, and idleTime = 0
if (console) console.log("User was warned of impending logoff");
}
function ResetIdleTime() {
// user did something; reset idle counter
idleTime = 0;
if (console) console.log("Idle time reset to 0");
}
$(document) // various events that can reset idle time
.on("mousemove", ResetIdleTime)
.on("click", ResetIdleTime)
.on("keydown", ResetIdleTime)
.children("body")
.on("scroll", ResetIdleTime);