[英]How to know browser idle time?
如何跟蹤瀏覽器空閑時間? 我正在使用IE8。
我沒有使用任何會話管理,也不想在服務器端處理它。
以下是純JavaScript方式來跟蹤空閑時間以及何時達到某個限制執行某些操作:
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.
此代碼將在顯示警報和重定向之前等待60秒,任何操作都將“重置”計數 - 鼠標單擊,鼠標移動或按鍵。
它應該盡可能地跨瀏覽器,並且直截了當。 如果您向ID為SecondsUntilExpire
頁面添加元素,它還支持顯示剩余時間。
上面的代碼應該可以正常工作,但有幾個缺點,例如它不允許任何其他事件運行,也不支持多重標簽。 包含以下兩者的重構代碼如下:(無需更改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";
}
}
上面重構的代碼使用本地存儲來跟蹤計數器上次重置的時間,並在每個打開的包含代碼的新選項卡上重置它,然后所有選項卡的計數器都相同,並重置為一個將導致重置所有選項卡。 由於Stack Snippets不允許本地存儲,所以在那里托管它是沒有意義的,所以我做了一個小提琴: http : //jsfiddle.net/yahavbr/gpvqa0fj/3/
回復太遲了,但這可能有助於有人寫出干凈實用的解決方案。 當您不需要顯示會話到期時間時,這是一個理想的解決方案。 很好地忽略了setInterval()
,它繼續在應用程序運行時運行腳本。
var inactivityTimeOut = 10 * 1000, //10 seconds inactivitySessionExpireTimeOut = ''; setSessionExpireTimeOut(); function setSessionExpireTimeOut () { 'use strict'; clearSessionExpireTimeout(); inactivitySessionExpireTimeOut = setTimeout(function() { expireSessionIdleTime(); }, inactivityTimeOut); } function expireSessionIdleTime () { 'use strict'; console.log('user inactive for ' + inactivityTimeOut + " seconds"); console.log('session expired'); alert('time expired'); clearSessionExpireTimeout(); document.location.href = "logout.html"; } function clearSessionExpireTimeout () { 'use strict'; clearTimeout(inactivitySessionExpireTimeOut); }
Running example: Timeout alert will be popped up in 10 seconds
希望這是你正在尋找的jquery-idletimer-plugin
這是一種使用jquery的方法,因為我需要保留文檔上現有的鍵盤事件。
我還需要在不同的空閑時間做不同的事情,所以我把它包裝在一個函數中
var onIdle = function (timeOutSeconds,func){
//Idle detection
var idleTimeout;
var activity=function() {
clearTimeout(idleTimeout);
console.log('to cleared');
idleTimeout = setTimeout(func, timeOutSeconds * 1000);
}
$(document).on('mousedown mousemove keypress',activity);
activity();
}
onIdle(60*60,function(){
location.reload();
});
onIdle(30,function(){
if(currentView!=='welcome'){
loadView('welcome');
}
});
我需要一個類似的東西並創建它: https : //github.com/harunurhan/idlejs
它在某種程度上簡單,可配置且功能強大,沒有任何依賴性。 這是一個例子。
import { Idle } from 'idlejs/dist';
// with predefined events on `document`
const idle = new Idle()
.whenNotInteractive()
.within(60)
.do(() => console.log('IDLE'))
.start();
您還可以使用自定義事件目標和事件
const idle = new Idle()
.whenNot([{
events: ['click', 'hover'],
target: buttonEl,
},
{
events: ['click', 'input'],
target: inputEl,
},
])
.within(10)
.do(() => called = true)
.start();
(用打字稿寫成並編譯成es5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.