Google Analytics, track page unload event

The request will not be synchronous, GA tracking calls never are.

The only way to ensure the call completes is to make sure the page stays open long enough - for an event on a link you would normally do this with a timeout potentially combined with a hitCallback, as you mentioned.

The only way to keep a window open when the user closes a tab is to return a value from your beforeunload handler, which will prompt a "Confirm Navigation" alert. That would be a really bad solution just to track a GA event, obviously.


There is a way to make sure the request will be sent to GA. Simo Ahava wrote a very good blog post titled -
"Leverage useBeacon And beforeunload In Google Analytics".

Utilizing the brilliant sendBeacon solution. Here's quote which addresses the selected answer of this question:

User agents will typically ignore asynchronous XMLHttpRequests made in an unload handler. To solve this problem, analytics and diagnostics code will typically make a synchronous XMLHttpRequest in an unload or beforeunload handler to submit the data. The synchronous XMLHttpRequest forces the User Agent to delay unloading the document, and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance.

There are other techniques used to ensure that data is submitted. One such technique is to delay the unload in order to submit data by creating an Image element and setting its src attribute within the unload handler. As most user agents will delay the unload to complete the pending image load, data can be submitted during the unload. Another technique is to create a no-op loop for several seconds within the unload handler to delay the unload and submit data to a server.

Not only do these techniques represent poor coding patterns, some of them are unreliable and also result in the perception of poor page load performance for the next navigation.