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?
The idle time is the time that the user has no interaction with the web-page. It can be mouse movement, page click or when the user uses the keyboard. The idle time can be detected using either vanilla JavaScript or jQuery code.
These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress. The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With