Vue中监听窗口关闭事件并在窗口关闭前发送请求
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue中监听窗口关闭事件并在窗口关闭前发送请求相关的知识,希望对你有一定的参考价值。
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: {
beforeunloadHandler(){
this._beforeUnload_time=new Date().getTime();
},
unloadHandler(e){
this._gap_time=new Date().getTime()-this._beforeUnload_time;
debugger
//判断是窗口关闭还是刷新
if(this._gap_time<=5){
//如果是登录状态,关闭窗口前,移除用户
if(!this.showLoginButton){
$.ajax({
url: ‘/pictureweb/user/remove‘,
type: ‘get‘,
async:false, //或false,是否异步
})
}
}
},
}
window.beforeunload事件在window.unload事件之前执行。同时注意ajax请求方式必须为同步请求,所以不能使用axios,因为axios不能执行同步请求。
分享一些技术学习视频资料:https://pan.baidu.com/s/13dbR69NLIEyP1tQyRTl4xw
以上是关于Vue中监听窗口关闭事件并在窗口关闭前发送请求的主要内容,如果未能解决你的问题,请参考以下文章
如何在flutter web中监听(“关闭”事件)文件下载窗口?