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

5
  • This is nothing to do with C# or ASP.NET Commented Jul 21, 2012 at 10:02
  • @freefaller - sure it does it is just worded wrong. Commented Jul 21, 2012 at 10:03
  • @Hogan and user1166862, my apologies... I was being too quick for my own good, I thought it was simply how to show the dialog. My apologies again Commented Jul 21, 2012 at 10:08
  • @freefaller - Don't apologize, your question is fine, I was waiting for someone else to answer it. Commented Jul 21, 2012 at 10:15
  • Microsoft talks a great deal about this issue including your exact question here : msdn.microsoft.com/en-us/library/aa479302.aspx Commented Jul 21, 2012 at 10:22

2 Answers 2

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
    }
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

and on the C# you have to have the click event defined for btnSave
@yogi Could you explain how to use window.confirm() with __doPostBack? Tried the codes above but there wasn't any prompt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.