Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.
Historically, you would send an AJAX request in the beforeunload
function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.
Luckily, we now have navigator.sendBeacon()
. By using the sendBeacon()
method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page. Here is an example of its usage:
window.addEventListener("unload", logData, false);
function logData() {
navigator.sendBeacon("/log.php", analyticsData);
}
sendBeacon()
is supported in:
- Edge 14
- Firefox 31
- Chrome 39
- Safari 11.1
- Opera 26
- iOS Safari 11.4
It is NOT currently supported in:
- Internet Explorer
- Opera Mini
Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.
0
Created by mike on 2020-03-11 20:09:19 +0000 UTC
Share