xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

埋点 & 数据上报 & 数据异常处理

埋点 & 数据上报 & 数据异常处理

如何在用户关闭浏览器前面,发送请求

  1. beforeunload

  2. 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');

虽然有效,但是用户需要等待请求结束才可以关闭页面; 对用户的体验不好;

  1. 发送异步请求,并且在服务端忽略ajax的abort;

虽然异步请求会被浏览器 abort,但是如果服务端可以忽略abort,仍然正常执行;
比如PHP有ignore_user_abort函数可以忽略abort。
这样需要改造后台,一般不太可行;

3. navigator.sendBeacon

最佳方案

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);

refs

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 发布文章使用:只允许注册用户才可以访问!


posted @ 2019-12-06 23:18  xgqfrms  阅读(180)  评论(3编辑  收藏  举报