如何使用JavaScript检测用户不活动?

3

我想要一个WordPress页面,在一段时间内没有活动后自动注销。目前我只是在测试“检测不活动并执行操作”的部分(关键部分)。我在这里找到了一些代码,部分代码可以工作;以下是代码:

<script>
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 10000);
}
</script>

目前它被设置为每10秒发送一次警报,这样我可以立即看到它是否在工作(以后会更长)。 无论如何,当我在页面上运行它时,它什么也不做。 我可以坐在那里5分钟,什么也不发生。 但是,如果我离开浏览器中的该选项卡,它会立即开始工作,并在没有活动的情况下每10秒发送一次警报。

但是,如果我只是坐在那个页面上什么也不做,整个功能都不起作用。 有人能帮忙解决吗? 谢谢...


当你只是在控制台中输入这个,但什么都不做时,当然什么也不会发生。计时器将通过你进行的第一次鼠标移动来初始化... - undefined
3个回答

13

请尝试使用这个方法:

function onInactive(ms, cb){

    var wait = setTimeout(cb, ms); 
    document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function(){
        clearTimeout(wait);
        wait = setTimeout(cb, ms);
    };
}

JSFiddle:

http://jsfiddle.net/acNfy/4

您需要将鼠标悬停在右下窗口上并保持不活动状态5秒钟才能看到结果 :)


4
被接受的答案有一个缺点,就是它会覆盖这些事件上任何已存在的事件处理程序。在这里有几个更优秀、更安全的解决方案:https://dev59.com/CHRB5IYBdhLWcg3wSVm1。 - undefined
谢谢!@imbondbaby - undefined
正如@grahamesd所说,这里的答案更完整:https://dev59.com/CHRB5IYBdhLWcg3wSVm1 - undefined
太感谢你帮了我这么多!非常感谢! - undefined

1
我喜欢在不活动时移除监听器,这是一个快速检测“无交互”的示例:
const IDLE_TIMEOUT = 5000; // in milliseconds
const idle_events = {
    load: false,
    mousemove: false,
    mousedown: false,
    touchstart: false,
    touchmove: false,
    keydown: false,
    click: false,
    scroll: true
}
let time;

function sendIdleEvent() {
    removeListeners()

    // Do something here
    // ...
}

function resetIdleTimeout() {
    clearTimeout(time)
    time = setTimeout(sendIdleEvent, IDLE_TIMEOUT)
}

function addListeners() {
    Object.entries(idle_events).forEach(([event_name, capture]) => {
        window.addEventListener(event_name, resetIdleTimeout, capture)
    })
}

function removeListeners() {

    Object.entries(idle_events).forEach(([event_name, capture]) => {
        window.removeEventListener(event_name, resetIdleTimeout, capture)
    })
}

addListeners()
resetIdleTimeout()

只需更改IDLE_TIMEOUT值为您希望认为用户没有交互的时间,并在sendIdleEvent函数内添加所需操作。
通过添加或删除“监听器”,您可以准确定义什么是“无交互”。

-3

我会尝试在窗口加载时触发超时。

之前回答不完整,我为此道歉。递归的setTimeout可能是你要找的。

(function interaction(){
    setTimeout(function(){
    // check for movement,
    if(movement...) {
        // if movement do nothing
        }
    else {
        interaction();



    },10000);

})();

嗨Motti:谢谢你的回复;但是我真的不确定你的意思,你能否进一步解释或提供更多信息?谢谢... - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接