Sometimes you may need to tell the server that the user is leaving the page. This is useful, for example, for cleaning unsaved images temporarily stored on a server, for marking this user as "offline", or for logging in when they are running in their session.
Historically, you sent an AJAX request to the beforeunload function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request will be executed correctly. If you send a synchronous request, it is more reliable, but the browser will freeze until the request is completed. If this is a slow request, this will be a huge inconvenience for the user.
Fortunately, we now have navigator.sendBeacon() . Using the sendBeacon() method, data is transferred asynchronously to the web server when the user agent is able to do this without delaying the upload or affecting the performance of the next navigation. This solves all the problems with providing analytical data: the data is sent reliably, it is sent asynchronously, and this does not affect the loading of the next page. Here is an example of its use:
window.addEventListener("unload", logData, false); function logData() { navigator.sendBeacon("/log.php", analyticsData); }
sendBeacon() supported in:
- Edge 14
- Firefox 31
- Chrome 39
- Safari 11.1
- Opera 26
- iOS Safari 11.4
It is currently not supported:
- Internet explorer
- opera mini
Here is the polyfield for sendBeacon () if you need to add support for unsupported browsers. If this method is not available in the browser, it will send a synchronous AJAX request instead.
Mike Sep 19 '18 at 18:52 2018-09-19 18:52
source share