The main challenge here is to execute the JavaScript function before the user actually leaves the page, the problem is that handling the onbeforeunload
event, 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:
From MSDN
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
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
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function showConfirmOnLeave() {
return $("#showConfirm").prop("checked");
}
function onLeavePage() {
if (showConfirmOnLeave()) {
return "Don't goo";
}
else {
return undefined;
}
}
$(function () {
if ($("body").attr('onbeforeunload') == null) {
$("body").attr('onbeforeunload', 'return onLeavePage(event)');
}
$(window).unload(function (event) {
if (showConfirmOnLeave()) {
window.open(
'<%: this.ResolveClientUrl("~/CallOnLeave.aspx") %>',
"_blank",
"height=100, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no, width=100, left=1, top=1",
false
);
}
});
});
</script>
<input type="checkbox" id="showConfirm" /> Show confirm on exit?
CallOnLeave.ASPX code behind
protected void Page_Load(object sender, EventArgs e)
{
// add here your custom code, ideally fire a new async thread to execute your commands on the background
}