VUE listens to the closing and hiding of web pages

1. Monitor the closing of the webpage and execute the exit operation

1. Create a monitor for page shutdown in mounted()

window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
window.addEventListener("unload", (e) => this.unloadHandler(e));

 2. The monitoring is before the page is closed, and the corresponding method can be written as

// 页面关闭之前,触发提示框
    beforeunloadHandler(e) {
      if (e) {
        e = e || window.event;
        console.log(e);
        if (e) {
          e.returnValue = "关闭提示";
        }
        return "关闭提示";
      }
    },

3. The listener is when the page is closed, where you can call your own asynchronous processing

  async myfuncation(e) {
      // 
      await &&**********
  },

4. Destroyed (), logout listener

destroyed() {
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
    window.removeEventListener("unload", (e) => this.unloadHandler(e));
  },

 2. VUE listens to the hidden display of the web page

mounted(){
    //添加监听事件
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));

    document.addEventListener('visibilitychange',function(e){
      console.log(document.visibilityState);
      let state = document.visibilityState
      if(state == 'hidden'){
        console.log(document.visibilityState,'用户离开了');
      }
      if(state == 'visible'){
        console.log(document.visibilityState,'回来了');
      }
    });

  }

Guess you like

Origin blog.csdn.net/qq_42717015/article/details/129944355