jQuery UI Dialog OnBeforeUnload
The correct way to display the alert is to simply return a string. Don't call the alert()
method yourself.
<script type="text/javascript">
$(window).on('beforeunload', function() {
if (iWantTo) {
return 'you are an idiot!';
}
});
</script>
See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
You can also make an exception for leaving the page via submitting a particular form:
$(window).bind('beforeunload', function(){
return "Do you really want to leave now?";
});
$("#form_id").submit(function(){
$(window).unbind("beforeunload");
});
this works for me
$(window).bind('beforeunload', function() {
return 'Do you really want to leave?' ;
});
jQuery API specifically says not to bind to beforeunload, and instead should bind directly to the window.onbeforeunload, I just ran across a pretty bad memory in part due binding to beforeunload with jQuery.
This works for me:
window.addEventListener("beforeunload", function(event) {
event.returnValue = "You may have unsaved Data";
});