Vue中监听浏览器窗口关闭事件,并在窗口关闭进行操作

  • window.onload事件 设置页面加载时执行的动作,即进入页面的时候执行的动作

  • window.onunload 已经从服务器上读到了需要加载的新的页面,在即将替换掉当前页面时调用一般用于设置当离开页面以后执行的动作

  • window.onbeforeunload 是正要去服务器读取新的页面时调用,此时还没开始读取,简单来说就是 在离开页面前的,一般用做提醒问你是不是要离开这个页面

onunload和onbeforeunload都是在页面刷新和关闭前的动作,但是onbeforeunload是先于onunload的,并且 onunload是无法阻止页面的更新和关闭的。而 Onbeforeunload 可以做到

页面加载:onload
页面关闭:onbeforeunload →onunload
页面刷新:onbeforeunload →onunload→onload

在 MDN Web Docs 是这样介绍 window.onunload的:
在这里插入图片描述

最终代码整合,可以自己放开 debugger 进行断点测试:

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 (e) {
      // debugger
      this._beforeUnload_time = new Date().getTime()
      console.log('this._beforeUnload_time:', this._beforeUnload_time)
      e = e || window.event
      if (e) {
        e.returnValue = '关闭提示'
      }
      // debugger
      return '关闭提示'
    },
    unloadHandler () {
      console.log('this._beforeUnload_time2:', this._beforeUnload_time)
      this._gap_time = new Date().getTime() - this._beforeUnload_time
      console.log('this._gap_time:', this._gap_time)
      // 判断是窗口关闭还是刷新
      if (this._gap_time <= 5) {
        // debugger
        // 如果是登录状态,关闭窗口前,移除用户
        if (!this.showLoginButton) {
          $.ajax({
            url: '/pictureweb/user/remove',
            type: 'get',
            async: false // 或false,是否异步

          })
        }
      } else {
        // debugger
      }
    }
  }

2021.9.3 更新

判断网页页面是否关闭或刷新的方法:
主要是针对网页版的页面,判断触发onbeforeunload事件的时候 :
1. 鼠标是否点击了关闭按钮;
2. 是否按了ALT+F4;
这两种方式来关闭网页,如果是,则认为系统是关闭网页,否则在认为系统是刷新网页。

window.onbeforeunload = function (event) {
  alert ("===οnbefοreunlοad===");
  if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
    alert ("你关闭了浏览器");
  } else {
    alert ("你正在刷新页面");
  }
}
  • 5
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值