Redirect user after 60 seconds of idling/inactivity?

旧城冷巷雨未停 提交于 2019-12-05 23:47:45

问题


How can I use JavaScript on my site to redirect the user to a /logout page after 60 seconds of inactivity?

I know setting a timer or using a meta refresh tag is straightforward: but I only want to redirect inactive users, not disrupt someone's active session/usage.

Is this possible with JavaScript?


回答1:


I belive you are looking for something like this:
http://paulirish.com/2009/jquery-idletimer-plugin/

If you were to code that yourself, you would need to capture mouse and keyboard events and restart your timer after any of these events. If the timer ever reaches the threshold or counts down to 0 from the threshold you can reset the URL of the page.




回答2:


Instead of using a plugin with unnecessary Kbytes, all you need is a simple function like this
(see explanation in comments):

<script>
(function() {

    const idleDurationSecs = 60;    // X number of seconds
    const redirectUrl = '/logout';  // Redirect idle users to this URL
    let idleTimeout; // variable to hold the timeout, do not modify

    const resetIdleTimeout = function() {

        // Clears the existing timeout
        if(idleTimeout) clearTimeout(idleTimeout);

        // Set a new idle timeout to load the redirectUrl after idleDurationSecs
        idleTimeout = setTimeout(() => location.href = redirectUrl, idleDurationSecs * 1000);
    };

    // Init on page load
    resetIdleTimeout();

    // Reset the idle timeout on any of the events listed below
    ['click', 'touchstart', 'mousemove'].forEach(evt => 
        document.addEventListener(evt, resetIdleTimeout, false)
    );

})();
</script>

If you want to redirect to the home page (usually at /), change '/logout' to '/':

    const redirectUrl = '/';  // Redirect idle users to the root directory

If you want to reload/refresh the current page, simply change '/logout' in the code above to location.href:

    const redirectUrl = location.href;  // Redirect idle users to the same page



回答3:


There is also a more up-to-date version of the plugin.

It will be able to fire idle event on entire document or single elements. For example mouse over some element for x seconds and it fires an event. Another event is fired when user becomes active again.

This idle event will allow you to redirect user after given time of inactivity.

Supported activity: mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove

https://github.com/thorst/jquery-idletimer



来源:https://stackoverflow.com/questions/5631307/redirect-user-after-60-seconds-of-idling-inactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!