I am working on a project where I need to capture the browser close event (unload
or beforeunload
). For that I have tried the code below but it's not working.
The code is working only if I open the browser console window (maybe just for a second) but it is required otherwise it's not working.
$(window).on('beforeunload', function(e) {
$.ajax({
type: "POST",
url: "url",
data : {'value' : 1},
dataType:'json'
});
return false;
});
The beacon API is meant specifically for that. Sending a request as the page is unloading. https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API