Can I prevent window.onbeforeunload from being called when doing an AJAX call

Paul picture Paul · Feb 11, 2009 · Viewed 31k times · Source

I have an AJAX-based grid control.

We hook into the window.onbeforeunload event to check if they have unsaved data and if so present them with a message "Are you sure you want to navigate away...you have unsaved data...".

All this is good.

But AJAX calls also trigger window.onbeforeunload and so if the grid has unsaved data and we make an AJAX call (such as to delete a row in another grid) the user gets the "Are you sure you want to navigate away...you have unsaved data..." message which is not good.

Is it possible to suppress the onbeforeunload event for AJAX calls? Or is it possible to detect that a call is an AJAX call? Otherwise we'll have to get hacking!

Thanks

Answer

cygro picture cygro · Mar 24, 2010

If you want to trigger your postback by a hyperlink, there is a simple workaround: Instead of

<a href="javascript:submitFunction();">Submit</a>

or

<a href="javascript:;" onclick="submitFunction();">Submit</a>

just use this code:

<a href="#" onclick="submitFunction();">Submit</a>

It seems that IE fires the onbeforeunload event if the content of the href-attribute of a hyperlink is not the current page (which the sharp character indicates).