有些网页需要监测用户的鼠标键盘动作是否停止以便执行相应的功能。
比如在线听课的网站,每隔一段时间就会弹出一道随机的题目让学员答题,以防止学员没真实在电脑前学习,
如果用户在5秒内鼠标键盘没有动作,则自动停止播放学习视频。
这种功能对于一般的学员是够用了。
但如果是遇到会编程的学员,他会自己写程序模拟人工答题,模拟人工自动键盘鼠标操作,那就需要更高级的防作弊方法了。
下面是监测键盘鼠标5秒内若无响应则自动执行某功能的javascript源码:
function ScreenSaver(settings){
this.settings = settings;
this.nTimeout = this.settings.timeout;
document.body.screenSaver = this;
// link in to body events
document.body.onmousemove = ScreenSaver.prototype.onevent;
document.body.onmousedown = ScreenSaver.prototype.onevent;
document.body.onkeydown = ScreenSaver.prototype.onevent;
document.body.onkeypress = ScreenSaver.prototype.onevent;
var pThis = this;
var f = function(){pThis.timeout();}
this.timerID = window.setTimeout(f, this.nTimeout);
}
ScreenSaver.prototype.timeout = function(){
if ( !this.saver ){
window.location = 'www.baidu.com';
}
}
ScreenSaver.prototype.signal = function(){
if ( this.saver ){
this.saver.stop();
}
window.clearTimeout(this.timerID);
var pThis = this;
var f = function(){pThis.timeout();}
this.timerID = window.setTimeout(f, this.nTimeout);
}
ScreenSaver.prototype.onevent = function(e){
this.screenSaver.signal();
}
var saver;
function initScreenSaver(){
//blort;
saver = new ScreenSaver({timeout:5000}); //无动作时间
}
window.onload = function(){
initScreenSaver();
}