Я, наконец, получил это работает для моего сайта. Я нашел ответ Эквимана самым полезным. Проблема с этим ответом состоит в том, что функция alert()
в javascript приостанавливает выполнение скрипта. Приостановка выполнения является проблемой, если вы хотите, как я сделал, отправить уведомление, а затем, если не получен ответ для автоматического выхода из системы.
Решение состоит в том, чтобы заменить alert()
пользовательским делением, описанным здесь .
Вот код: ( ПРИМЕЧАНИЕ : вам нужно изменить строку 58, чтобы перенаправить на соответствующий URL для вашего сайта)
var inactivityTracker = function () {
// Create an alert division
var alertDiv = document.createElement("div");
alertDiv.setAttribute("style","position: absolute;top: 30%;left: 42.5%;width: 200px;height: 37px;background-color: red;text-align: center; color:white");
alertDiv.innerHTML = "You will be logged out in 5 seconds!!";
// Initialise a variable to store an alert and logout timer
var alertTimer;
var logoutTimer;
// Set the timer thresholds in seconds
var alertThreshold = 3;
var logoutThreshold = 5;
// Start the timer
window.onload = resetAlertTimer;
// Ensure timer resets when activity logged
registerActivityLoggers(resetAlertTimer);
// ***** FUNCTIONS ***** //
// Function to register activities for alerts
function registerActivityLoggers(functionToCall) {
document.onmousemove = functionToCall;
document.onkeypress = functionToCall;
}
// Function to reset the alert timer
function resetAlertTimer() {
clearTimeout(alertTimer);
alertTimer = setTimeout(sendAlert, alertThreshold * 1000);
}
// Function to start logout timer
function startLogoutTimer() {
clearTimeout(logoutTimer);
logoutTimer = setTimeout(logout, logoutThreshold * 1000);
}
// Function to logout
function sendAlert() {
// Send a logout alert
document.body.appendChild(alertDiv);
// Start the logout timer
startLogoutTimer();
// Reset everything if an activity is logged
registerActivityLoggers(reset);
}
// Function to logout
function logout(){
//location.href = 'index.php';
}
// Function to remove alert and reset logout timer
function reset(){
// Remove alert division
alertDiv.parentNode.removeChild(alertDiv);
// Clear the logout timer
clearTimeout(logoutTimer);
// Restart the alert timer
document.onmousemove = resetAlertTimer;
document.onkeypress = resetAlertTimer;
}
};
<html>
<script type="text/javascript" src="js/inactivityAlert.js"></script>
<head>
<title>Testing an inactivity timer</title>
</head>
<body onload="inactivityTracker();" >
Testing an inactivity timer
</body>
</html>