如何知道浏览器的空闲时间? [英] How to know browser idle time?

查看:408
本文介绍了如何知道浏览器的空闲时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何追踪浏览器的空闲时间?我使用IE8。

我没有使用任何会话管理和不想处理它在服务器端。


解决方案

下面是纯JavaScript的方式来跟踪空闲时间,当它达到一定限度做一些动作:

\r
\r

VAR IDLE_TIMEOUT = 60; //秒\r
VAR _idleSecondsTimer = NULL;\r
变种_idleSecondsCounter = 0;\r
\r
document.onclick =功能(){\r
    _idleSecondsCounter = 0;\r
};\r
\r
document.onmousemove =功能(){\r
    _idleSecondsCounter = 0;\r
};\r
\r
document.onkey preSS =功能(){\r
    _idleSecondsCounter = 0;\r
};\r
\r
_idleSecondsTimer = window.setInterval(CheckIdleTime,1000);\r
\r
功能CheckIdleTime(){\r
     _idleSecondsCounter ++;\r
     变种oPanel =的document.getElementById(SecondsUntilExpire);\r
     如果(oPanel)\r
         oPanel.innerHTML =(IDLE_TIMEOUT ​​- _idleSecondsCounter)+;\r
    如果(_idleSecondsCounter> = IDLE_TIMEOUT){\r
        window.clearInterval(_idleSecondsTimer);\r
        警报(时间过期!​​);\r
        document.location.href =logout.html;\r
    }\r
}

\r

#SecondsUntilExpire {背景颜色:黄色; }

\r

您将自动上述&lt注销;跨度ID =SecondsUntilExpire> < / SPAN>秒。

\r

\r
\r

这code将等待60秒显示警报和重定向之前,任何行动将复位伯爵 - 鼠标点击,鼠标移动或按键preSS

它应该是跨浏览器成为可能,和直线前进。它也支持显示剩余时间,如果你用的ID SecondsUntilExpire 元素添加到您的网页。

以上code应该工作正常,但是有几个缺点,例如它不允许任何其它事件来运行,不支持多重标签。重构code,包括这两个是以下几点:(无需更改HTML)

  VAR IDLE_TIMEOUT = 60; //秒
VAR _localStorageKey ='global_countdown_last_reset_timestamp';
VAR _idleSecondsTimer = NULL;
VAR _lastResetTimeStamp =(新的Date())的getTime()。
VAR _localStorage = NULL;的attachEvent(文件,点击,重新设定时间);
的attachEvent(文件,鼠标移动,重新设定时间);
的attachEvent(文件,'键preSS',重新设定时间);
的attachEvent(窗口'负荷',重新设定时间);尝试{
    _localStorage = window.localStorage;
}
赶上(前){
}_idleSecondsTimer = window.setInterval(CheckIdleTime,1000);功能GetLastResetTimeStamp(){
    变种lastResetTimeStamp = 0;
    如果(_localStorage){
        lastResetTimeStamp = parseInt函数(_localStorage [_localStorageKey],10);
        如果(isNaN(lastResetTimeStamp)|| lastResetTimeStamp℃下)
            lastResetTimeStamp =(新的Date())的getTime()。
    }其他{
        lastResetTimeStamp = _lastResetTimeStamp;
    }    返回lastResetTimeStamp;
}功能SetLastResetTimeStamp(时间戳){
    如果(_localStorage){
        _localStorage [_localStorageKey] =的timeStamp;
    }其他{
        _lastResetTimeStamp =的timeStamp;
    }
}功能重新设定(){
    (。(新的Date())的getTime())SetLastResetTimeStamp;
}功能的attachEvent(元素,eventName的,事件处理){
    如果(element.addEventListener){
        element.addEventListener(eventName的,事件处理程序,FALSE);
        返回true;
    }否则如果(element.attachEvent){
        element.attachEvent('上'+ eventName的,事件处理程序);
        返回true;
    }其他{
        //无关,浏览器太旧或非标准反正
        返回false;
    }
}功能WriteProgress(MSG){
    变种oPanel =的document.getElementById(SecondsUntilExpire);
    如果(oPanel)
         oPanel.innerHTML =味精;
    否则,如果(控制台)
        的console.log(味精);
}功能CheckIdleTime(){
    VAR currentTimeStamp =(新的Date())的getTime()。
    变种lastResetTimeStamp = GetLastResetTimeStamp();
    变种secondsDiff = Math.floor((currentTimeStamp - lastResetTimeStamp)/ 1000);
    如果(secondsDiff&下; = 0){
        重新设定时间();
        secondsDiff = 0;
    }
    WriteProgress((IDLE_TIMEOUT ​​- secondsDiff)+);
    如果(secondsDiff> = IDLE_TIMEOUT){
        window.clearInterval(_idleSecondsTimer);
        重新设定时间();
        警报(时间过期!​​);
        document.location.href =logout.html;
    }
}

在重构code以上使用本地存储来跟踪当计数器最后复位,并且还重置它包含code在打开每一个新的选项卡,然后计数器将是同为所有选项卡,并在一个复位,将导致所有选项卡的复位。由于栈片断不允许本地存储,这是毫无意义的还有主办,所以我做了一个小提琴:
http://jsfiddle.net/yahavbr/gpvqa0fj/3/

How can I track the browser idle time? I am using IE8.

I am not using any session management and don't want to handle it on server side.

解决方案

Here is pure JavaScript way to track the idle time and when it reach certain limit do some action:

var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsTimer = null;
var _idleSecondsCounter = 0;

document.onclick = function() {
    _idleSecondsCounter = 0;
};

document.onmousemove = function() {
    _idleSecondsCounter = 0;
};

document.onkeypress = function() {
    _idleSecondsCounter = 0;
};

_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);

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

#SecondsUntilExpire { background-color: yellow; }

You will be auto logged out in <span id="SecondsUntilExpire"></span> seconds.

​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.

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.

The above code should work fine, however has several downsides, e.g. it does not allow any other events to run and does not support multiply tabs. Refactored code that include both of these is following: (no need to change HTML)

var IDLE_TIMEOUT = 60; //seconds
var _localStorageKey = 'global_countdown_last_reset_timestamp';
var _idleSecondsTimer = null;
var _lastResetTimeStamp = (new Date()).getTime();
var _localStorage = null;

AttachEvent(document, 'click', ResetTime);
AttachEvent(document, 'mousemove', ResetTime);
AttachEvent(document, 'keypress', ResetTime);
AttachEvent(window, 'load', ResetTime);

try {
    _localStorage = window.localStorage;
}
catch (ex) {
}

_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);

function GetLastResetTimeStamp() {
    var lastResetTimeStamp = 0;
    if (_localStorage) {
        lastResetTimeStamp = parseInt(_localStorage[_localStorageKey], 10);
        if (isNaN(lastResetTimeStamp) || lastResetTimeStamp < 0)
            lastResetTimeStamp = (new Date()).getTime();
    } else {
        lastResetTimeStamp = _lastResetTimeStamp;
    }

    return lastResetTimeStamp;
}

function SetLastResetTimeStamp(timeStamp) {
    if (_localStorage) {
        _localStorage[_localStorageKey] = timeStamp;
    } else {
        _lastResetTimeStamp = timeStamp;
    }
}

function ResetTime() {
    SetLastResetTimeStamp((new Date()).getTime());
}

function AttachEvent(element, eventName, eventHandler) {
    if (element.addEventListener) {
        element.addEventListener(eventName, eventHandler, false);
        return true;
    } else if (element.attachEvent) {
        element.attachEvent('on' + eventName, eventHandler);
        return true;
    } else {
        //nothing to do, browser too old or non standard anyway
        return false;
    }
}

function WriteProgress(msg) {
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
         oPanel.innerHTML = msg;
    else if (console)
        console.log(msg);
}

function CheckIdleTime() {
    var currentTimeStamp = (new Date()).getTime();
    var lastResetTimeStamp = GetLastResetTimeStamp();
    var secondsDiff = Math.floor((currentTimeStamp - lastResetTimeStamp) / 1000);
    if (secondsDiff <= 0) {
        ResetTime();
        secondsDiff = 0;
    }
    WriteProgress((IDLE_TIMEOUT - secondsDiff) + "");
    if (secondsDiff >= IDLE_TIMEOUT) {
        window.clearInterval(_idleSecondsTimer);
        ResetTime();
        alert("Time expired!");
        document.location.href = "logout.html";
    }
}

The refactored code above is using local storage to keep track of when the counter was last reset, and also reset it on each new tab that is opened which contains the code, then the counter will be the same for all tabs, and resetting in one will result in reset of all tabs. Since Stack Snippets do not allow local storage, it's pointless to host it there so I've made a fiddle: http://jsfiddle.net/yahavbr/gpvqa0fj/3/

这篇关于如何知道浏览器的空闲时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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