Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent the user to change page with jQuery

I have a page with a form that is submittes via ajaxSubmit() (so, without changing the page).

My goal is that, when the user try to change page (or even to close the browser), i ask him if really want to exit the page without sending the form (exactly as gmail does).

Gmail for example do this with a window.confirm-like popup, but if it is possible, i'll like to handle it with custom messages and options.

jQuery have the unload event:

$(window).unload( function () { alert("Bye now!"); } );

but it permits me just to do something before exit the page; i need to 'block' the page exit, if the user click the relative button.

So, how to handle (and cancel) the page-exit event?

like image 326
Strae Avatar asked Jul 09 '09 08:07

Strae


2 Answers

try the following. Demo here

<script type="text/javascript">

       function unloadPage(){
           return "dont leave me this way";
       }

       window.onbeforeunload = unloadPage;

</script>
like image 165
redsquare Avatar answered Sep 20 '22 06:09

redsquare


It's possible bind the "onbeforeunload" event with jQuery:

$(window).bind('beforeunload', function(e) {
    return "ATTENZIONE!!";
});

It works!!

like image 23
Sergio Avatar answered Sep 18 '22 06:09

Sergio