window.addEventListener('unload', function(event) {
var xhr = new XMLHttpRequest(),
data = captureAnalyticsData(event);
xhr.open('post', '/log', false);
xhr.send(data);
});
function captureAnalyticsData(event) {
return 'sample data';
}
注意xhr.open('post', '/log', false)
的第三个参数,
false为同步请求,也就是document unload之前必须等待请求发出并响应;
true表示异步请求,在document unload时容易被浏览器遗弃。
https://github.com/huangwenming/learning-notes/tree/master/html-relevant/beacon
关键截图: beacon请求:
xhr请求:
https://www.sitepoint.com/introduction-beacon-api/