##上报内容 脚本错误 浏览时间 404信息 链接点击数量
在页面发生错误时或关闭页面,分别对应error
和unload
事件。
error
事件会在其回掉函数中传入一个ErrorEvent
类型的参数。ErrorEvent
包含了全面的错误信息,其中有错误描述,文件名,行列号和Even对象。
##上报方式
- 被动上报:使用error和unload事件触发
- 主动上报:使用try-catch捕获异常
**注意:**对于使用error
事件上报错误时,需要注意跨域问题,对于跨域的脚本必须要在HTTP返回头中加入Access-Control-Allow-Origin
属性,然后在引用该JS脚本的script
标签中加入crossorigin
属性,否则浏览器会将ErrorEvent
重的message
属性替换成替换为Script error.
。
##数据发送方式
在页面unload时,如果要上报当前数据,采用xhr的同步上报方式,会阻塞当前页面的跳转;使用new Image有可能遇到aborted,导致无法成功发送。
window.addEventListener('unload', function(event) {
(new Image).src = 'http://example.com/s.gif?......';
});
文档卸载期间发送数据,浏览器继续保持阻塞状态,等数据发送出去后再跳转,这里存在的问题是:
BOM对象下的sendBeacon方法。sendBeacon是异步的,不会影响当前页到下一个页面的跳转速度,且不受同域限制。Google Analytics也用的是这种方式。
window.addEventListener('unload', logData, false);
function logData() {
navigator.sendBeacon("/log", analyticsData);
}
navigator.sendBeacon || new Function('var xhr=new XMLHttpRequest();xhr.open("POST",arguments[0],false);r.send(arguments[1]);');
参考文章: Navigator.sendBeacon()