You add an onbeforeunload event to your body element: onbeforeunload="beforeUnloadForm();"
This would become like:
<body onload="initForm();" onbeforeunload="beforeUnloadForm();">
and in the javascript function you put something like this:
function beforeUnloadForm()
{
if (window.hasChangesPending)
{
window.event.returnValue = "Pending changes have not been saved.";
}
}
When trying to leave the page or close the browser the user now must confirm.
Good luck!
Ps. I do not know if you get a chance to execute code after the user confirmed. But you could already send it to the server and handle it after a certain time out or discard if the user hits cancel.