通过浏览器检测用户不活动 - 纯粹通过javascript [英] Detecting user inactivity over a browser - purely through javascript

查看:149
本文介绍了通过浏览器检测用户不活动 - 纯粹通过javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在构建监视器时,监视器将监视用户在浏览器上的任何活动,例如单击按钮或在文本框上键入(而不是鼠标悬停在文档上)。因此,如果用户长时间没有活动,会话将超时。

In building a monitor, which would monitor any activity on the browser by the user, like click of a button or typing on a textbox (not mouse hovering on document). So if there is no activity from the user for a long time, the session will time out.

我们需要在没有jquery或其他类似的情况下执行此操作。我可以使用ajax。另一端的java servlet更可取。

We need to do it without jquery or anything such. I may use ajax. java servlet in other end is preferable.

推荐答案

这是纯粹的JavaScript方式来跟踪空闲时间,当它达到某个限制时做一些动作,你可以相应地修改并使用

Here is pure JavaScript way to track the idle time and when it reach certain limit do some action, you can modify accordingly and use

var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsCounter = 0;
document.onclick = function() {
    _idleSecondsCounter = 0;
};
document.onmousemove = function() {
    _idleSecondsCounter = 0;
};
document.onkeypress = function() {
    _idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    _idleSecondsCounter++;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        alert("Time expired!");
        document.location.href = "logout.html";
    }
}

此代码将在显示警报和重定向之前等待60秒,任何动作都会重置计数 - 鼠标点击,鼠标移动或按键。

This code will wait 60 seconds before showing alert and redirecting, and any action will "reset" the count - mouse click, mouse move or key press.

它应尽可能是跨浏览器,并且直截了当。它还支持显示剩余时间,如果您向ID为SecondsUntilExpire的页面添加元素。

It should be as cross browser as possible, and straight forward. It also support showing the remaining time, if you add element to your page with ID of SecondsUntilExpire.

参考:如何知道浏览器空闲时间?

这篇关于通过浏览器检测用户不活动 - 纯粹通过javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆