js/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()方法之前执行
    },
    // 关闭
    unloadHandler(){
      this._gap_time = new Date().getTime() - this._beforeUnload_time
      if (this._gap_time <= 5) {
        console.log('0000000000000000000000000000000000')
        // 浏览器关闭操作
      }
    }
 }

你可能感兴趣的:(javascript,前端,vue.js)