Requirements: judge the user's activity, and log out directly if the user is inactive for more than 30 minutes.
I wanted to record the time of the last request at the beginning, and use the time of the last request to judge the user's activity. It's a little limited.
Search the Internet, said to use the mouse movement state to detect whether the operation page. It's not bad at all, but it's a way. So...
// Detect user activity
function isActive() {
var arr = ['index', 'login']
var result = arr.some(function(item) {
return window.location.href.indexOf(item) > 0
})
// result indicates that the current page may be index or registration page
// It's not the index page, it's not the registration page to detect the user's active state (mouse moving state)
if (!result) {
var lastTime = new Date().getTime();
var currentTime = new Date().getTime();
//Set timeout: 10 points
var timeOut = 10 * 60 * 1000;
window.onload = function() {
/* Detect mouse movement events */
document.addEventListener('mousemove', function() {
// Update last action time
console.log('The mouse is moving')
lastTime = new Date().getTime();
})
}
/* Timer interval 1 minute, check whether the page has not been operated for a long time */
var quitTime = window.setInterval(testTime, 60000);
// Timeout function
function testTime() {
//Update current time
currentTime = new Date().getTime();
console.log('currentTime', currentTime)
//Judge whether it is timeout
if (currentTime - lastTime > timeOut) {
// console.log('timeout pull ')
// Overtime operation
axios.post(logoutUrl,params)
.then(function (res) {
// Write time-out code, such as logout and so on
})
.catch(function (error) {
console.log(error);
});
// Clear timer
window.clearInterval(quitTime)
}
}
}
}
isActive()