- 销毁页面事件
window.addEventListener('beforeunload', function(event){
event.preventDefault();
event.returnValue = '';
alert('要卸载吗');
});
- api
navigator.sendBeacon(url, 数据);
- 注意事项:
- 默认是发post请求,后端需要能够post接收数据
- Beacon API不提供相应的回调,因此后端返回最好省略response body,(例如,204 No Content)
- navigator.sendBeacon()之后的代码可以执行
window.addEventListener('beforeunload', function(event){
let sendData = JSON.stringify({
page: window._pageName||location.href,
timeStamp: Date.now()
})
navigator.sendBeacon('http://localhost:9999/logs', sendData);
});