Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:
window.onbeforeunload=function(e){
// only take action (iterate) if my SCHEDULED_REQUEST object contains data
for (var key in SCHEDULED_REQUEST){
postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
for (var i=0;i<1000;i++){
// do something unnoticable but time consuming like writing a lot to console
console.log('buying some time to finish saving data');
};
break;
};
}; // no return string --> user will leave as normal but data is send to server
Edit: See also Synchronous_AJAX and how to do that with jquery