You should use onbeforeunload as follows:
<script type="text/javascript"> saved=true; // initially, it is saved (no action has been done) window.onbeforeunload = confirmExit; function confirmExit() { if (!saved) { return "You did not save, do you want to do it now?"; } } </script>
This event cannot be processed only when another event is fired. The onchange event of your text field here probably does not fire before you click on the link so that the window does not process onbeforeunload at all. The link will work as expected: you will be redirected.
To deal with the saved flag, you can listen to what is happening in your text field, for example, when the user is actually typing:
$('textarea').keyup(function(){ saved=false; });
Then, if you save the data in ajax, the save button can return true:
$('#btnSave').click(function(){
Otherwise, it will load the next page with the saved flag.
source share