项目需求,关闭浏览器记录登出日志,那么意思就是关闭浏览器要掉登出的接口这样来记录登出日志。可是问题来了,关闭浏览器会强制取消接口,也就是在监测浏览器关闭事件里面不会执行接口函数,alert()和console.log()也不会执行,经过我得实验测试,可以进行在浏览器的localStorage缓存里存值。
具体实现如下:app.vue页面代码如下
mounted() {
// 监听浏览器关闭
window.addEventListener('beforeunload', (e) => { this.beforeunloadHandler(e) });
window.addEventListener('unload', (e) => { this.unloadHandler(e) });
}
destroyed() {
// 移除监听
window.removeEventListener('beforeunload', (e) => { this.beforeunloadHandler(e) });
window.removeEventListener('unload', (e) => { this.unloadHandler(e) });
},
methods: {
// 关闭窗口之前执行
/* 这样关闭和刷新窗口的时候都会提示
遇到问题:
1、如果打开界面没有任何操作,包括单机界面,是不会出发一下事件的
2、修改提示文字好像没有起作用。 */
beforeunloadHandler(e) {
this.beforeUnload_time = new Date().getTime();
/* window.isCloseHint = true 增加了提示之后,不增加提示,关闭浏览器就不会执行里面的操作了
// 初始化关闭
if (window.isCloseHint) {
const confirmationMessage = '您确定要关闭窗口吗?';
(e || window.event).returnValue = confirmationMessage
return confirmationMessage
} */
},
unloadHandler(e) {
var currTime = this.$moment(new Date().getTime()).format('YYYY-MM-DD hh:mm:ss')
this.gap_time = new Date().getTime() - this.beforeUnload_time;
// 判断是窗口关闭 毫秒数判断 存值 来判断关闭过浏览器,和关闭浏览器的时间,存起来,用于登录页面登录之后,继续掉登出接口,把关闭浏览器的时间传给接口记录下来
if (this.gap_time <= 10) {
storage.set('isLogout', true)
storage.set('logoutTime', currTime)
storage.remove('language')
storage.remove('Admin-Token')
} else {
// 窗口刷新
// storage.set('isLogout', false)
}
}
}
login.vue页面代码如下:
点击登录之后掉退出登录的接口 进行记录日志
// 掉退出接口 传入退出的时间(退出的时间从localStorage.get('logoutTime'))获取 从而实现关闭浏览器 记录登出日志
/* const params = {
logoutTime: storage.get('logoutTime')// 退出登录时间参数 待定
} */
// 需要区分 是登出日志没有关闭浏览器和关闭浏览器字段来判断调用记录日志接口
if (storage.get('isLogout') && storage.get('logoutTime')) {
this.loginOutFun() // todo 接口需要增加退出登录时间参数
}
好了大概思路就是这样子啦!