The question is a duplicate (I should have realized that at the time). I've posted a version of this answer here on the other question and made this a Community Wiki.
Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page). Although you can't do PUT with it, the replacement for synchronous ajax in unload handlers is sendBeacon
. sendBeacon
lets you send data to your server without holding up the page you're doing it in:
window.addEventListener("unload", function() {
navigator.sendBeacon("/log", yourDataHere);
});
The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).
Beacons are POSTs, not PUTs, but other than that it's exactly what you're looking for.
Note that the unload
event may not be reliable, particularly on mobile devices. You might combine the above with sending a beacon on visibilitychange
as well.