Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 364
Paul Avatar asked Feb 11 '09 16:02

Paul


People also ask

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What is the difference between Onbeforeunload and Onunload?

onbeforeunload Below are my findings on the iPad; Using window. onunload , I am able to get an alert when user navigates to a different page from myPage. html (either by clicking on some link or doing a Google search while on myPage.

What does Window Onbeforeunload do?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


1 Answers

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).

like image 156
cygro Avatar answered Sep 20 '22 13:09

cygro