Have a look at the JavaScript function window.onbeforeunload
.
Essentially, browsers fire this event when they detect that the page is closing, and allow you to customize a message by returning a string from this function.
You cannot however, control if the user wants to force close the page early, or unexpectedly.
window.onbeforeunload = function(e) {
// do some ajax post here
//
// Display a message (or generic message in some browsers) and allow the user to cancel leaving the page.
return 'Dialog text here.';
};
Note that this solution tries to warn the user and allows the unload to be cancelled. This might not be ideal for you, but should work.
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload