I think the best possible way would be to check if the user changed anything. If so then store this and confirm that the user really wants to exit the page. Something like:
function beforeClose(){
if(inputChanged){
return 'Are you sure you want to navigate away?';
}
}
Above also looks kind of user friendly. I also was thinking about something else but I haven't tested this. The idea is to setup a timer and return false and let the timer event handle the saving and closing of the page. You probably will need a global variable to keep track if saving is already done, otherwise closing will never work.
var isSaved = false;
<body onbeforeunload="if (!isSaved) {setTimeout('handleWindowClose();',50);return false;}">
function handleWindowClose()
{
isSaved = true;
}
Good luck!