I am beginner web developer. I make my first project in Laravel and Vue. I need to make:
- Auto-logout after 3 minutes - when user is inactive
- Auto ping to my token (domain/api/refresh).
I try do it in a function in my main.js:
setTimeout(function() {
window.location.href = "domain/logout";
}, 30000);
for refresh, but it's run only one time - when I page reload.
How can I make it? Please help me :)
I am beginner web developer. I make my first project in Laravel and Vue. I need to make:
- Auto-logout after 3 minutes - when user is inactive
- Auto ping to my token (domain./api/refresh).
I try do it in a function in my main.js:
setTimeout(function() {
window.location.href = "domain./logout";
}, 30000);
for refresh, but it's run only one time - when I page reload.
How can I make it? Please help me :)
Share Improve this question edited Oct 29, 2021 at 8:42 codejockie 10.9k4 gold badges48 silver badges57 bronze badges asked Oct 29, 2021 at 8:39 tarafikttestarafikttes 1371 gold badge3 silver badges13 bronze badges 4- How you detect if user is inactive or active ? – Vasile Radeanu Commented Oct 29, 2021 at 8:42
-
check out the
v-idle
ponent:https://github./malekim/v-idle
. Simply do <v-idle @idle="logout()" /> – zoltalar Commented Oct 29, 2021 at 9:10 - <v-idle @idle="onidle" @remind="onremind" :loop="true" :reminders="[10, 15]" :wait="5" :duration="300" /> methods: { onidle() { alert('You have been logged out'); }, onremind(time) { // alert seconds remaining to 00:00 alert(time); } } – tarafikttes Commented Oct 29, 2021 at 10:36
- In which file I must add this code? I need this timeout in all app – tarafikttes Commented Oct 29, 2021 at 10:37
1 Answer
Reset to default 5You can use the following events mousemove
, mousedown
, keypress
, and touchdown
to determine whether a user is active. You will need two functions, one to start the timer and the other to reset it. The reset will be used for the aforementioned events.
In your main.js, do this:
const timeoutInMS = 180000; // 3 minutes -> 3 * 60s * 1000ms
let timeoutId;
function handleInactive() {
// Here you want to logout a user and/or ping your token
}
function startTimer() {
// setTimeout returns an ID (can be used to start or clear a timer)
timeoutId = setTimeout(handleInactive, timeoutInMS);
}
function resetTimer() {
clearTimeout(timeoutId);
startTimer();
}
function setupTimers () {
document.addEventListener("keypress", resetTimer, false);
document.addEventListener("mousemove", resetTimer, false);
document.addEventListener("mousedown", resetTimer, false);
document.addEventListener("touchmove", resetTimer, false);
startTimer();
}
Then call setupTimers
on page load.
NOTE: The above code is one way you could detect if a user is inactive.