浏览器关闭前调用 区分刷新和关闭
因为业务需要 要在浏览器关闭前调用异步接口 且浏览器刷新时不调用该接口
问题 1.浏览器关闭是异步请求发送会中断解决方法
fetch keepalive:true
window
.fetch("http://10.224.196.18:8081/monitor/login/xxxx.action", {
method: "POST",
// headers: headers,
headers: {
token: Cookie.get("token"),
username: Cookie.get("userName"),
password: Cookie.get("password"),
},
keepalive: true,
})
.then((res) => {});
问题 2. 浏览器刷新和关闭调用的相同方法
以谷歌为例
刷新:页面刷新前先调用 onbeforeunload,在新页面即将替换旧页面时onunload,最后onload
关闭: 页面关闭前调用onbeforeunload,再onunload
页面刷新的时候先onbeforeunload,然后取服务端请求数据,在新页面即将替换旧页面时进入onunload.
而页面关闭时是先onbeforeunload,然后立即进入onunload事件.
所以 刷新时第一步到第二步肯定比关闭时用的时间长.
完整代码如下
var _beforeUnload_time = 0,
_gap_time = 0; //_gap_time时间差
window.onunload = function () {
_gap_time = new Date().getTime() - _beforeUnload_time;
if (_gap_time <= 10) {
console.log("1");
console.log(_gap_time); //guanbi
window
.fetch("http://10.224.196.18:8081/monitor/login/xxx.action", {
method: "POST",
// headers: headers,
headers: {
token: Cookie.get("token"),
username: Cookie.get("userName"),
password: Cookie.get("password"),
},
keepalive: true,
})
.then((res) => {});
} else {
console.log("3333333");
console.log(_gap_time);
} //shuanxi
};
window.onbeforeunload = function () {
_beforeUnload_time = new Date().getTime();
};