vue监听浏览器窗口关闭

vue监听浏览器窗口关闭

需求:后端需要在用户退出或者关闭页面的时候调用一个接口
相关技术点
页面关闭和刷新时, 触发 beforeunload事件
当文档或一个子资源正在被卸载时, 触发 unload事件,unload在beforeunload之后被触发

参考了网上大家分享的一些方法后,根据自身实际情况调整后可用~
参考网址:https://blog.csdn.net/robin90814/article/details/90603369

第一步 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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值