vue 监听浏览器关闭事件
vue 监听浏览器关闭事件用vue做的项目,有个需求就是关闭浏览器的时候,需要往后台提交有个接口,来监听这个账号有没有下线。第一步 data里放好要用到的变量//声明遍历data() {return {_beforeUnload_time:'',_gap_time:'',}}第二步 监听mounted() {window.addEventListener('beforeunload', e =&g
·
vue 监听浏览器关闭事件
用vue做的项目,有个需求就是关闭浏览器的时候,需要往后台提交有个接口,来监听这个账号有没有下线。
第一步 data里放好要用到的变量
//声明遍历
data() {
return {
_beforeUnload_time:'',
_gap_time:'',
}
}
第二步 监听
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))
},
第三步 必须使用同步请求
此处用的是post方法,默认的contentType接口报错了。
设置好contentType后,报错‘unexpected token o in JSON at position ’ ,后端拿不到值。将参数先用JSON.stringify()转成 JSON字符串就好了。
methods: {
beforeunloadHandler(e){
this._beforeUnload_time = new Date().getTime();
//e.returnValue = '关闭提示'; 弹窗
},
unloadHandler(e){
this._gap_time = new Date().getTime() - this._beforeUnload_time;
//判断是窗口关闭还是刷新
if (this._gap_time <= 5) {
let datas = {
objCode:null,
opertion:'退出登录ajax',
param:null,
path:null,,}
datas = JSON.stringify(datas)
$.ajax({
url: this.$apiUrl.user.oper,
type: 'post',
contentType:'application/json',
data:datas,
dataType: "json",
async: false, //或false,是否异步
})
}
},
},
更多推荐
已为社区贡献1条内容
所有评论(0)