需求:为了防止页面待机时间过长,导致再操作时token过期报错的问题,要求每隔半小时检查一次用户是否有进行过任何操作,未进行操作直接登出系统(类似于各大银行App一定时间内未操作直接退出登录)。
思路:在layout布局页面设置定时器监听当前时间戳和上一次操作存储的时间戳的大小比较。监听鼠标的移动事件或点击事件,鼠标操作时更新上一次存储的操作时间,直至用户长时间未操作,当前时间戳大于上一次存储的操作时间戳,清空token,退回到登录界面。
saveLastTime(){
localStorage.setItem("lastClickTime", new Date().getTime());
},
isTimeOut() {
// 使用定时器之前,要清除一下定时器
clearInterval(this.timer);
this.timer = setInterval(() => {
let lastClickTime = localStorage.getItem("lastClickTime") * 1; // 把上次点击时候的字符串时间转换成数字时间
let nowTime = new Date().getTime(); // 获取当前时间
// 假设我们需求是:半个钟不进行点击操作,就提示登录退出
if (nowTime - lastClickTime > 1000 * 1800) {
// 提示一下用户
message.warn('长时间未操作,已退出登录')
// 这里要清除定时器,结束任务
clearInterval(this.timer);
logout();
removeToken();
localStorage.clear();
// 清除 socket 监听
const socket = getInstance();
if (socket && socket.isReady) {
socket.close();
}
// 最后返回到登录页
this.$router.push({ path: "/login" });
}
}, 1000);
},
created () {
window.addEventListener(
"mousemove",
this.saveLastTime,
true
);
},
mounted () {
this.isTimeOut();
}
beforeDestroy() {
clearInterval(this.timer);
},
destroyed(){
window.removeEventListener("mousemove", this.saveLastTime, true);
},