区分浏览器的刷新和浏览器的关闭

需求: 在关闭浏览器时发送请求,刷新时不发送请求。

方法一

1.在 mounted中,加入回调函数

   window.addEventListener("unload", (e) => this.unloadHandler(e));
   window.addEventListener("load", (e) => this.loadHandler(e));

2.定义函数

  unloadHandler(e) {
      // 判断是刷新还是关闭网站
    let unloadDate = new Date().getTime() + "";
    sessionStorage.setItem("unload_time", unloadDate);
    setTimeout(() => {
        // 在里面打印或者debbug都是无效的,不显示
        // 但是关闭浏览器时,数据会存到sessionStorage里面去,同域名可见
      let loadDate = localStorage.getItem("_load_Time");
      // 打开两个窗口,同域名下可以查看localStorage数据
      if (!loadDate || Number(unloadDate) >= Number(loadDate)) {
           // 刷新的时候,不进来
          // 关闭的时候进来
          // 验证
        localStorage.setItem("closeBrowser", "1"); // 会存入成功!!!!!!
        // 不能进行请求,发送请求无效
        fetch(`/usr/app1`, {
          method: "GET",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: sessionStorage.getItem("token"),
          },
          mode: "same-origin",
          keepalive: true,
        });
        });
      }
    });
  }
  loadHandler(e) {
    let nowDate = new Date().getTime() + "";
    sessionStorage.setItem("_load_Time", nowDate);
  }  

方法二

在vue /angular单页面中:
    window.onbeforeunload = function () {
      this.beginTime = new Date().getTime();
    };
    window.onunload = function () {
      this.differTime = new Date().getTime() - this.beginTime;
      if (this.differTime <= 5) {
        // 关闭
        window.localStorage.setItem("isPagesClose", this.differTime);
        const params = [
          `caseId=${this._currentChatId}`,
          `customerId=${this._customerId}`,
        ].join("&");
        let promise = fetch(`/api/session-unconnected?${params}`, {
          method: "GET",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: `Bearer ${sessionStorage.getItem("token")}`,
          },
          mode: "same-origin",
          keepalive: true,
        });
        // 大概率成功,会将请求得到的值存入到localStroge中
        window.localStorage.setItem("success", JSON.stringify(promise));
      } else {
        // 刷新
        window.localStorage.setItem("isPagesLoad", this.differTime);
      }
    };
    window.onload = function () {
      console.log("onload");
    };
  }

你可能感兴趣的:(angular开发问题)