如果用户当前在页面上处于活动状态,我如何使用JavaScript / jQuery进行检测?

时间:2021-07-27 06:07:43

I am needing to detect when a user is inactive (not clicking or typing) on the current page for more than 30 minutes.

我需要在当前页面上检测用户何时处于非活动状态(不是单击或键入)超过30分钟。

I thinking it might be best to use event blubbling attached to the body tag and then just keep resetting a timer for 30 minutes, but I'm not exactly sure how to create this.

我认为最好使用贴在身体标签上的事件blubbling,然后继续重置计时器30分钟,但我不确定如何创建它。

I have jQuery available, although I'm not sure how much of this will actually use jQuery.

我有jQuery可用,虽然我不确定这有多少实际上会使用jQuery。

Edit: I'm more needing to know if they are actively using the site, therefore clicking (changing fields or position within a field or selecting checkboxes/radios) or typing (in an input, textarea, etc). If they are in another tab or using another program, then my assumption is they are not using the site and therefore should be logged out (for security reasons).

编辑:我更需要知道他们是否正在积极使用该网站,因此单击(更改字段或字段内的位置或选择复选框/无线电)或键入(在输入,textarea等)。如果他们在另一个选项卡或使用其他程序,那么我的假设是他们没有使用该网站,因此应该注销(出于安全原因)。

Edit #2: So everyone is clear, this is not at all for determining if the user is logged in, authenticated or anything. Right now the server will log the user out if they don't make a page request within 30 minutes. This functionality to prevent the times when someone spends >30 minutes filling in a form and then submitting the form only to find out that they haven't been logged out. Therefore, this will be used in combination with the server site to determine if the user is inactive (not clicking or typing). Basically, the deal is that after 25 minutes of idle, they will be presented with a dialog to enter their password. If they don't within 5 minutes, the system automatically logs them out as well as the server's session is logged out (next time a page is accessed, as with most sites).

编辑#2:所以每个人都清楚,这根本不是用于确定用户是否已登录,经过身份验证或其他任何内容。现在,如果用户在30分钟内没有发出页面请求,服务器会将用户注销。此功能可防止有人花费> 30分钟填写表单然后提交表单以发现他们尚未注销的时间。因此,这将与服务器站点结合使用,以确定用户是否处于非活动状态(不是单击或键入)。基本上,这笔交易是在闲置25分钟后,他们会看到一个输入密码的对话框。如果他们不在5分钟内,系统会自动将其注销,并且服务器的会话将被注销(下次访问页面时,与大多数站点一样)。

The Javascript is only used as a warning to user. If JavaScript is disabled, then they won't get the warning and (along with most of the site not working) they will be logged out next time they request a new page.

Javascript仅用作对用户的警告。如果JavaScript被禁用,那么他们将不会收到警告(并且大部分网站都不工作),他们将在下次请求新页面时注销。

10 个解决方案

#1


14  

You can watch mouse movement, but that's about the best you're going to get for indication of a user still being there without listening to the click event. But there is no way for javascript to tell if it is the active tab or if the browser is even open. (well, you could get the width and height of the browser and that'd tell you if it was minimized)

您可以观看鼠标移动,但这是关于用户仍然在那里而不是听取点击事件的最佳情况。但javascript无法判断它是否为活动标签或浏览器是否打开。 (好吧,你可以得到浏览器的宽度和高度,并告诉你它是否被最小化)

#2


22  

This is what I've come up with. It seems to work in most browsers, but I want to be sure it will work everywhere, all the time:

这就是我想出来的。它似乎适用于大多数浏览器,但我想确保它始终可以在任何地方使用:

var timeoutTime = 1800000;
var timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime);
$(document).ready(function() {
    $('body').bind('mousedown keydown', function(event) {
        clearTimeout(timeoutTimer);
        timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime);
    });
});

Anyone see any problems?

有谁看到任何问题?

#3


15  

I just recently did something like this, albeit using Prototype instead of JQuery, but I imagine the implementation would be roughly the same as long as JQuery supports custom events.

我刚刚做了类似的事情,虽然使用Prototype而不是JQuery,但我想只要JQuery支持自定义事件,实现就会大致相同。

In a nutshell, IdleMonitor is a class that observes mouse and keyboard events (adjust accordingly for your needs). Every 30 seconds it resets the timer and broadcasts an state:idle event, unless it gets a mouse/key event, in which case it broadcasts a state:active event.

简而言之,IdleMonitor是一个观察鼠标和键盘事件的类(根据您的需要进行相应调整)。每30秒重置计时器并广播一个状态:idle事件,除非它获得鼠标/键事件,在这种情况下它会广播一个状态:active事件。

var IdleMonitor = Class.create({

    debug: false,
    idleInterval: 30000, // idle interval, in milliseconds
    active: null,
    initialize: function() {
        document.observe("mousemove", this.sendActiveSignal.bind(this));
        document.observe("keypress", this.sendActiveSignal.bind(this));
        this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);
    },

    // use this to override the default idleInterval
    useInterval: function(ii) {
        this.idleInterval = ii;
        clearTimeout(this.timer);
        this.timer = setTimeout(this.sendIdleSignal.bind(this), ii);
    },

    sendIdleSignal: function(args) {
        // console.log("state:idle");
        document.fire('state:idle');
        this.active = false;
        clearTimeout(this.timer);
    },

    sendActiveSignal: function() {
        if(!this.active){
            // console.log("state:active");
            document.fire('state:active');
            this.active = true;
            this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);
        }
    }
});

Then I just created another class that has the following somewhere in it:

然后我刚刚创建了另一个在其中包含以下内容的类:

Event.observe(document, 'state:idle', your-on-idle-functionality);
Event.observe(document, 'state:active', your-on-active-functionality)

#4


15  

Ifvisible.js is a crossbrowser lightweight solution that does just that. It can detect when the user switches to another tab and back to the current tab. It can also detect when the user goes idle and becomes active again. It's pretty flexible.

Ifvisible.js是一个交叉浏览器轻量级解决方案。它可以检测用户何时切换到另一个选项卡并返回当前选项卡。它还可以检测用户何时进入空闲状态并再次变为活动状态。它非常灵活。

#5


3  

Using jQuery, you can easily watch mouse movement, and use it to set a variable indicating activity to true, then using vanilla javascript, you can check this variable every 30 minutes (or any other interval) to see if its true. If it's false, run your function or whatever. Look up setTimeout and setInterval for doing the timing. You'll also probably have to run a function every minute or so to reset the variable to false.

使用jQuery,您可以轻松地观察鼠标移动,并使用它来设置指示活动为true的变量,然后使用vanilla javascript,您可以每隔30分钟(或任何其他间隔)检查此变量以查看其是否为真。如果它是假的,运行你的功能或其他什么。查找setTimeout和setInterval以进行计时。您可能还需要每分钟左右运行一个函数才能将变量重置为false。

#6


3  

Ifvisible is a nice JS lib to check user inactivity.

Ifvisible是一个很好的JS lib来检查用户是否不活动。

ifvisible.setIdleDuration(120); // Page will become idle after 120 seconds

ifvisible.on("idle", function(){
   // do something
});

#7


2  

Here my shot:

在这里我的镜头:

var lastActivityDateTime = null;

function checkActivity( )
{
    var currentTime = new Date();
    var diff = (lastActivityDateTime.getTime( ) - currentTime.getTime( ));
    if ( diff >= 30*60*1000)
    {
        //user wasn't active;
        ...
    }
    setTimeout( 30*60*1000-diff, checkActivity);
}

setTimeout( 30*60*1000, checkActivity); // for first time we setup for 30 min.


// for each event define handler and inside update global timer
$( "body").live( "event_you_want_to_track", handler);

function handler()
{
   lastActivityDateTime = new Date();
   // rest of your code if needed.
}

#8


2  

If it's a security issue, doing this clientside with javascript is absolutely the wrong end of the pipe to be performing this check. The user could easily have javascript disabled: what does your application do then? What if the user closes their browser before the timeout. do they ever get logged out?

如果这是一个安全问题,使用javascript执行此客户端绝对是执行此检查的管道的错误结束。用户可以轻松禁用javascript:您的应用程序会做什么?如果用户在超时之前关闭浏览器该怎么办他们有没有退出?

Most serverside frameworks have some kind of session timeout setting for logins. Just use that and save yourself the engineering work.

大多数服务器端框架都具有某种登录会话超时设置。只需使用它并节省您的工程工作。

You can't rely on the assumption that people cannot log in without javascript, therefore the user has javascript. Such an assumption is no deterrent to any determined, or even modestly educated attacker.

您不能依赖于人们无法在没有javascript的情况下登录的假设,因此用户拥有javascript。这种假设对任何坚定的,甚至是受过适度教育的攻击者都没有威慑作用。

Using javascript for this is like a security guard handing customers the key to the bank vault. The only way it works is on faith.

使用javascript就像一名保安人员将钥匙交给银行金库。它的唯一工作方式就是信仰。

Please believe me when I say that using javascript in this way (and requiring javascript for logins!!) is an incredibly thick skulled way to engineer any kind of web app.

当我说以这种方式使用javascript(并且需要javascript登录!!)时,请相信我,这是一种令人难以置信的厚厚的方式来设计任何类型的Web应用程序。

#9


1  

Without using JS, a simpler (and safer) way would simply be to have a lastActivity timestamp stored with the user's session and checking it on page load. Assuming you are using PHP (you can easily redo this code for another platform):

如果不使用JS,更简单(更安全)的方法就是将lastActivity时间戳存储在用户的会话中并在页面加载时进行检查。假设您使用的是PHP(您可以轻松地将此代码重做为另一个平台):

if(($_SESSION['lastAct'] + 1800) < time()) {
    unset($_SESSION);
    session_destroy();
    header('Location: session_timeout_message.php');
    exit;
}

$_SESSION['lastAct'] = time();

and add this in your page (optional, the user will be logged out regardless of if the page is refreshed or not (as he logs out on next page log)).

并在页面中添加(可选,无论页面是否刷新,用户都将被注销(因为他在下一页日志中注销))。

<meta http-equiv="refresh" content="1801;" /> 

#10


0  

If your concern is the lost of information for the user after a login timeout; another option would be to simply store all the posted information upon the opening of a new session (a new session will always be started when the older session has been closed/scrapped by the server) when the request to a page is made before re-routing to the logging page. If the user successfully login, then you can use this saved information to return the user back to where he was. This way, even if the user walk away a few hours, he can always return back to where he was after a successful login; without losing any information.

如果您担心在登录超时后丢失了用户的信息;另一种选择是在新会话开始时简单地存储所有发布的信息(当服务器关闭/报废旧会话时,将始终启动新会话)当对页面的请求发出之前路由到日志页面。如果用户成功登录,则可以使用此保存的信息将用户返回到他所在的位置。这样,即使用户走了几个小时,他也可以在成功登录后返回原来的位置;不丢失任何信息。

This require more work by the programmer but it's a great feature totally appreciated by the users. They especially appreciate the fact that they can fully concentrate about what they have to do without stressing out about potentially losing their information every 30 minutes or so.

这需要程序员更多的工作,但这是一个完全受用户赞赏的好功能。他们特别欣赏这样一个事实,即他们可以完全专注于他们必须做的事情,而不会强调每30分钟左右可能丢失他们的信息。

#1


14  

You can watch mouse movement, but that's about the best you're going to get for indication of a user still being there without listening to the click event. But there is no way for javascript to tell if it is the active tab or if the browser is even open. (well, you could get the width and height of the browser and that'd tell you if it was minimized)

您可以观看鼠标移动,但这是关于用户仍然在那里而不是听取点击事件的最佳情况。但javascript无法判断它是否为活动标签或浏览器是否打开。 (好吧,你可以得到浏览器的宽度和高度,并告诉你它是否被最小化)

#2


22  

This is what I've come up with. It seems to work in most browsers, but I want to be sure it will work everywhere, all the time:

这就是我想出来的。它似乎适用于大多数浏览器,但我想确保它始终可以在任何地方使用:

var timeoutTime = 1800000;
var timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime);
$(document).ready(function() {
    $('body').bind('mousedown keydown', function(event) {
        clearTimeout(timeoutTimer);
        timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime);
    });
});

Anyone see any problems?

有谁看到任何问题?

#3


15  

I just recently did something like this, albeit using Prototype instead of JQuery, but I imagine the implementation would be roughly the same as long as JQuery supports custom events.

我刚刚做了类似的事情,虽然使用Prototype而不是JQuery,但我想只要JQuery支持自定义事件,实现就会大致相同。

In a nutshell, IdleMonitor is a class that observes mouse and keyboard events (adjust accordingly for your needs). Every 30 seconds it resets the timer and broadcasts an state:idle event, unless it gets a mouse/key event, in which case it broadcasts a state:active event.

简而言之,IdleMonitor是一个观察鼠标和键盘事件的类(根据您的需要进行相应调整)。每30秒重置计时器并广播一个状态:idle事件,除非它获得鼠标/键事件,在这种情况下它会广播一个状态:active事件。

var IdleMonitor = Class.create({

    debug: false,
    idleInterval: 30000, // idle interval, in milliseconds
    active: null,
    initialize: function() {
        document.observe("mousemove", this.sendActiveSignal.bind(this));
        document.observe("keypress", this.sendActiveSignal.bind(this));
        this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);
    },

    // use this to override the default idleInterval
    useInterval: function(ii) {
        this.idleInterval = ii;
        clearTimeout(this.timer);
        this.timer = setTimeout(this.sendIdleSignal.bind(this), ii);
    },

    sendIdleSignal: function(args) {
        // console.log("state:idle");
        document.fire('state:idle');
        this.active = false;
        clearTimeout(this.timer);
    },

    sendActiveSignal: function() {
        if(!this.active){
            // console.log("state:active");
            document.fire('state:active');
            this.active = true;
            this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);
        }
    }
});

Then I just created another class that has the following somewhere in it:

然后我刚刚创建了另一个在其中包含以下内容的类:

Event.observe(document, 'state:idle', your-on-idle-functionality);
Event.observe(document, 'state:active', your-on-active-functionality)

#4


15  

Ifvisible.js is a crossbrowser lightweight solution that does just that. It can detect when the user switches to another tab and back to the current tab. It can also detect when the user goes idle and becomes active again. It's pretty flexible.

Ifvisible.js是一个交叉浏览器轻量级解决方案。它可以检测用户何时切换到另一个选项卡并返回当前选项卡。它还可以检测用户何时进入空闲状态并再次变为活动状态。它非常灵活。

#5


3  

Using jQuery, you can easily watch mouse movement, and use it to set a variable indicating activity to true, then using vanilla javascript, you can check this variable every 30 minutes (or any other interval) to see if its true. If it's false, run your function or whatever. Look up setTimeout and setInterval for doing the timing. You'll also probably have to run a function every minute or so to reset the variable to false.

使用jQuery,您可以轻松地观察鼠标移动,并使用它来设置指示活动为true的变量,然后使用vanilla javascript,您可以每隔30分钟(或任何其他间隔)检查此变量以查看其是否为真。如果它是假的,运行你的功能或其他什么。查找setTimeout和setInterval以进行计时。您可能还需要每分钟左右运行一个函数才能将变量重置为false。

#6


3  

Ifvisible is a nice JS lib to check user inactivity.

Ifvisible是一个很好的JS lib来检查用户是否不活动。

ifvisible.setIdleDuration(120); // Page will become idle after 120 seconds

ifvisible.on("idle", function(){
   // do something
});

#7


2  

Here my shot:

在这里我的镜头:

var lastActivityDateTime = null;

function checkActivity( )
{
    var currentTime = new Date();
    var diff = (lastActivityDateTime.getTime( ) - currentTime.getTime( ));
    if ( diff >= 30*60*1000)
    {
        //user wasn't active;
        ...
    }
    setTimeout( 30*60*1000-diff, checkActivity);
}

setTimeout( 30*60*1000, checkActivity); // for first time we setup for 30 min.


// for each event define handler and inside update global timer
$( "body").live( "event_you_want_to_track", handler);

function handler()
{
   lastActivityDateTime = new Date();
   // rest of your code if needed.
}

#8


2  

If it's a security issue, doing this clientside with javascript is absolutely the wrong end of the pipe to be performing this check. The user could easily have javascript disabled: what does your application do then? What if the user closes their browser before the timeout. do they ever get logged out?

如果这是一个安全问题,使用javascript执行此客户端绝对是执行此检查的管道的错误结束。用户可以轻松禁用javascript:您的应用程序会做什么?如果用户在超时之前关闭浏览器该怎么办他们有没有退出?

Most serverside frameworks have some kind of session timeout setting for logins. Just use that and save yourself the engineering work.

大多数服务器端框架都具有某种登录会话超时设置。只需使用它并节省您的工程工作。

You can't rely on the assumption that people cannot log in without javascript, therefore the user has javascript. Such an assumption is no deterrent to any determined, or even modestly educated attacker.

您不能依赖于人们无法在没有javascript的情况下登录的假设,因此用户拥有javascript。这种假设对任何坚定的,甚至是受过适度教育的攻击者都没有威慑作用。

Using javascript for this is like a security guard handing customers the key to the bank vault. The only way it works is on faith.

使用javascript就像一名保安人员将钥匙交给银行金库。它的唯一工作方式就是信仰。

Please believe me when I say that using javascript in this way (and requiring javascript for logins!!) is an incredibly thick skulled way to engineer any kind of web app.

当我说以这种方式使用javascript(并且需要javascript登录!!)时,请相信我,这是一种令人难以置信的厚厚的方式来设计任何类型的Web应用程序。

#9


1  

Without using JS, a simpler (and safer) way would simply be to have a lastActivity timestamp stored with the user's session and checking it on page load. Assuming you are using PHP (you can easily redo this code for another platform):

如果不使用JS,更简单(更安全)的方法就是将lastActivity时间戳存储在用户的会话中并在页面加载时进行检查。假设您使用的是PHP(您可以轻松地将此代码重做为另一个平台):

if(($_SESSION['lastAct'] + 1800) < time()) {
    unset($_SESSION);
    session_destroy();
    header('Location: session_timeout_message.php');
    exit;
}

$_SESSION['lastAct'] = time();

and add this in your page (optional, the user will be logged out regardless of if the page is refreshed or not (as he logs out on next page log)).

并在页面中添加(可选,无论页面是否刷新,用户都将被注销(因为他在下一页日志中注销))。

<meta http-equiv="refresh" content="1801;" /> 

#10


0  

If your concern is the lost of information for the user after a login timeout; another option would be to simply store all the posted information upon the opening of a new session (a new session will always be started when the older session has been closed/scrapped by the server) when the request to a page is made before re-routing to the logging page. If the user successfully login, then you can use this saved information to return the user back to where he was. This way, even if the user walk away a few hours, he can always return back to where he was after a successful login; without losing any information.

如果您担心在登录超时后丢失了用户的信息;另一种选择是在新会话开始时简单地存储所有发布的信息(当服务器关闭/报废旧会话时,将始终启动新会话)当对页面的请求发出之前路由到日志页面。如果用户成功登录,则可以使用此保存的信息将用户返回到他所在的位置。这样,即使用户走了几个小时,他也可以在成功登录后返回原来的位置;不丢失任何信息。

This require more work by the programmer but it's a great feature totally appreciated by the users. They especially appreciate the fact that they can fully concentrate about what they have to do without stressing out about potentially losing their information every 30 minutes or so.

这需要程序员更多的工作,但这是一个完全受用户赞赏的好功能。他们特别欣赏这样一个事实,即他们可以完全专注于他们必须做的事情,而不会强调每30分钟左右可能丢失他们的信息。