踩坑日记:在关闭浏览器窗口前向后端发送请求

110 阅读1分钟

场景:在关闭浏览器窗口前向后端发送请求

image.png 方法:通过window.addEventListener添加beforeunload事件监听,定义相应的函数发送相应的请求,然后移除事件监听。 坑:在移除监听的时候不能使用匿名函数,否则移除失败。

openDialog() {
  window.addEventListener('beforeunload', this.changeStatus)
  this.orderdialog = true
},
closeDialog() {
  this.orderdialog = false
  // 不要使用window.removeEventListener('beforeunload', e => { console.log(e) }, false)
  window.removeEventListener('beforeunload', this.changeStatus, false)
},
changeStatus(e) {
  if (e) {
    e.returnValue = '关闭提示'
  }
  const data = {
    wid: this.chosewid,
    status: 'offline'
  }
  if (!this.chosewid) return
  recordReplyStatus(data)
    .then(() => {
    })
    .catch(() => {
    })
},