I have the following javascript to prompt the user if he attempts to navigate away from the page. A dialog box will appear with 2 buttons ‘Leave this page’ and ‘Stay on this page’. I would like to cause a postback which will fire a C# Event.
I want this postback to occur when the ‘Leave this page’ button is pressed.
How can i do this? Pardon me i am quite new to Javascript.
<script type="text/javascript" language="JavaScript">
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
return "You have attempted to leave this page. This will CANCEL your current order selection.";
}
The main challenge here is to execute the JavaScript function before the user actually leaves the page, the problem is that handling the
onbeforeunloadevent, you cannot react to the user choice because in order for this event to work in multi-browser scenarios, you must return a string which will be used as the message, and each browser will create a custom dialog that will be shown to the user. I have not found a better approach, to do what you require. Basically you cannot override the default behavior in the browsers, and you cannot return a bool to indicate whether the page should be unloaded or not.For more info:
How can I override the OnBeforeUnload dialog and replace it with my own?
jQuery UI Dialog OnBeforeUnload
From MSDN
So in this example, I’m proposing a workaround, I’m not sure if this is the best approach, but I have seen behavior like this in several online banks and from Microsoft itself when logging out in their sites.
Example:
ASPX
CallOnLeave.ASPX code behind