参考这位老哥的博客
链接:link
话不多说,直接上代码
第一步
//可以封装成js,全局调用,如果是vue使用也可以写在App.vue文件的mounted中
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e)) //3
let isOpen = localStorage.getItem('isOpen')//1
let reload = localStorage.getItem('reload')//2
this.timer2=setTimeout(() => {
localStorage.removeItem('reload')//4
}, 2000);
console.log(isOpen, reload, isOpen == 'open', reload != 'reload', 'reload');
if (isOpen == 'open' && reload != 'reload') {
localStorage.removeItem('isOpen')
localStorage.removeItem('reload')
this.timer3= setTimeout(() => {
let open1=localStorage.getItem('isOpen')//7
let load1=localStorage.getItem('reload')
if (open1 == 'open'&&load1!=='reload') {
this.$alert('网站重复打开即将关闭', {
confirmButtonText: '确定',
callback: action => {
}
});
this.timer4= setTimeout(() => {
window.opener = null;
location.href = "about:blank";
window.close();
localStorage.removeItem('reload')
localStorage.removeItem('isOpen')//6
}, 2000)
}else{
history.go(0)
}
}, 1000)
} else {
setInterval(() => {
localStorage.setItem('isOpen', 'open')//5
}, 1000);
}
第二步 在methods中
beforeunloadHandler(e) { //根据事件进行操作进行操作
console.log(e)
console.log('浏览器刷新')
localStorage.setItem('reload', 'reload')
},
第三步 在destroyed
destroyed() { //进行监听销毁
localStorage.removeItem('isOpen')
localStorage.removeItem('reload')
clearTimeout(this.timer2)
clearTimeout(this.timer3)
clearTimeout(this.timer4)
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
},