2

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.";
}

Hogan
  • 69,564
  • 10
  • 76
  • 117
aurelio
  • 207
  • 1
  • 8
  • 18

2 Answers2

1

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
    }
Community
  • 1
  • 1
Jupaol
  • 21,107
  • 8
  • 68
  • 100
0

Use window.confirm() with __doPostBack

Something like this

window.onbeforeunload = confirmExit;
function confirmExit() {
    if (confirm("Want to exit ??"))
          __doPostBack('btnSave ', "exit confirmed");

}

For more on __doPostBack Go here

NOTE : window.onbeforeunload event raises when user clicks on close and window is about to close so it'll go server side for sure as I tested it but request will crash as the client has been closed, And your server side code execution will STOP. So it's not a better approach to do things.

Community
  • 1
  • 1
yogi
  • 19,175
  • 13
  • 62
  • 92
  • and on the C# you have to have the click event defined for btnSave – Hogan Jul 21 '12 at 10:17
  • @yogi Could you explain how to use window.confirm() with __doPostBack? Tried the codes above but there wasn't any prompt – aurelio Jul 21 '12 at 10:52