假设您正在进行银行应用程序.如果用户登录到您的站点,如何检测他们的不活动状态并要求他们在一段时间内保持不活动状态?这里处于非活动状态意味着他们要么切换到其他选项卡,要么不触摸浏览器应用程序.
我想我可以通过注册用户在我的应用程序的每个页面上进行的每个鼠标移动或键盘移动来做到这一点.但是代码会非常难看并且难以维护.还有其他更优雅的方式吗?
小智 15
嗨,大家好,这是我使用的代码.它不是我的,但我确实修改了它的'完美'.
// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
Run Code Online (Sandbox Code Playgroud)
好运
理查德