如何在用户关闭浏览器前面,发送请求
beforeunload
unload
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
window.addEventListener("beforeunload", function (event) {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
1: 发送同步的ajax请求
var oAjax = new XMLHttpRequest();
oAjax.open('POST', url + '/user/register', false);//false表示同步请求
oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oAjax.onreadystatechange = function() {
if (oAjax.readyState == 4 && oAjax.status == 200) {
var data = JSON.parse(oAjax.responseText);
} else {
console.log(oAjax);
}
};
oAjax.send('a=1&b=2');
虽然有效,但是用户需要等待请求结束才可以关闭页面; 对用户的体验不好;
虽然异步请求会被浏览器 abort,但是如果服务端可以忽略abort,仍然正常执行;
比如PHP有ignore_user_abort函数可以忽略abort。
这样需要改造后台,一般不太可行;
最佳方案
https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/sendBeacon
blob = new Blob([`room_id=123`], {type : 'application/x-www-form-urlencoded'});
navigator.sendBeacon("/cgi-bin/leave_room", blob);
var fd = new FormData();
fd.append('room_id', 123);
navigator.sendBeacon("/cgi-bin/leave_room", fd);
var params = new URLSearchParams({ room_id: 123 })
navigator.sendBeacon("/cgi-bin/leave_room", params);
https://developer.mozilla.org/en-US/docs/Web/API/Document/readystatechange_event
https://stackoverflow.com/questions/38027231/how-to-make-navigator-sendbeacon-use-get-method
https://usefulangle.com/post/63/javascript-navigator-sendbeacon-set-form-http-header
xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章