暂时没找到什么优美得解决办法,如遇到,请留言,谢谢
浏览器没有关闭事件,只有在关闭时会调用beforeunload,unload,但是再刷新时会调用beforeunload,unload,onload
因此关闭再打开与刷新区别在于再次打开的时间差
丑陋的解决办法:利用时间差
前提 token是保存在localstorage中
1.登录接口中添加本地存储参数
localStorage.setItem('pageInstanceNum', 1)
2.页面添加监听,此处时间差设置的时10秒,一般看接口请求最长时间
window.onload = function (e) {
if(localStorage.getItem('tokenName')) {let num = localStorage.getItem('pageInstanceNum') || 0if (num) {num = Number(num)}num = num + 1localStorage.setItem('pageInstanceNum', num)const gapTime = localStorage.getItem('closetime'); //获取关闭事件const openTime = new Date().getTime() - gapTime;localStorage.setItem('openTime', openTime)if (num == 1 && openTime > 10000) {localStorage.removeItem('tokenName')}}}
window.onbeforeunload = function (e) {if(localStorage.getItem('tokenName')) {localStorage.setItem('closetime', new Date().getTime()); //关闭let num = localStorage.getItem('pageInstanceNum') || 0if (num) {num = Number(num)}if(sessionStorage.getItem("sessionPageInstanceNum")){num = num - 1localStorage.setItem('pageInstanceNum', num)}}
}
3.需要在登录时,添加一个session的参数,我是在app.vue中添加
//update生命周期
updated() {if(isLogin && !sessionStorage.getItem("sessionPageInstanceNum")){//isLogin 判断是否已经登录的参数sessionStorage.setItem("sessionPageInstanceNum",1)}}
4.在logout登出函数中去除session的参数
sessionStorage.removeItem("sessionPageInstanceNum")