Reputation: 61
So ive been trying to make automatic logout, but i cannot find a way to logout after like 10secs after the alertbox (alertbox asks if you wanna logout if you havent still left the site but are browsing for some information and dont wanna log out) shows up automatically. Basically i wanna make it automatically logout if you dont press anything on the alertbox after chosen time like 10secs. Heres the code!
var refresh_rate = 5; // <-- In seconds, change to your needs
var reset_rate = 7; // <-- In seconds logs out after not pressing OK or cancel in automatic logout
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
var focus_margin = 10; // If we lose focus more then the margin we want to refresh
function reset() {
last_user_action = 0;
console.log("Reset");
}
function windowHasFocus() {
has_focus = true;
}
function windowLostFocus() {
has_focus = false;
lost_focus_count++;
console.log(lost_focus_count + " <~ Lost Focus");
}
setInterval(function () {
last_user_action++;
refreshCheck();
}, 1000);
function refreshCheck() {
var focus = window.onfocus;
if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
refresh_rate = 10;
}
else{
window.location.reload(); // If this is called no reset is needed
reset(); // We want to reset just to make sure the location reload is not called.
}
}
}
I hope someone can help me with this problem!
Upvotes: 0
Views: 164
Reputation: 1074575
You can't, if you use confirm
(or alert
or prompt
, any of those relics of the 1990s). They bring the main JavaScript thread to a screeching halt (mostly, there's nuance around this now), meaning you can't do anything else (mostly).
To do this, you need to replace the confirm
with a DOM element showing the message instead, which won't block the main JavaScript thread.
Upvotes: 1