.Net ramblings
# Monday, 24 April 2006
HowTo: cancel an onbeforeunload event
if you're like me and use the onbeforeunload event in a web page to display a reminder to a user who might unintentially lose work by browsing away from the page, then you might be trying to find a way to cancel the event in the case where the user clicks the save button (they obviously don't need reminding now that they have clicked the button...)

on the internet you will find many people suggesting you use something like
window.onbeforeunload = null
but this does not work for me in IE6.  reading up in the MSDN docs for the event object i found a reference to the event.cancelBubble property, which i thought was the solution. but thanks to Orso who pointed out that setting "event.cancelBubble=true" is useless, the way to get rid of the confirm prompt is to exclude the return statement altogether, i chose to use a boolean variable as a flag to decide whether to return something or not. in the example below i add the javascript code programattically in the code behind:

	Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", @"
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(postback == false)
return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";
}
</script>");

then my save button contains the following aspx markup:
    OnClientClick="postback=true;return true;"
this sets the 'postback' variable to true, which gets picked up in the confirmExit() function, having the effect of cancelling the event. 

hope you find this useful.  it is tested and works in IE6 and FF 1.5.0.2.


Monday, 24 April 2006 17:10:13 (GMT Daylight Time, UTC+01:00)  #    Comments [16]  Asp.Net

Wednesday, 19 September 2007 22:20:53 (GMT Daylight Time, UTC+01:00)
Hi Tim,

I am sorry that i could not make this work in my case. I tried this in a simple HTML page and io t wouldn't work for me.

I had this code in my HTML page

<script language="javascript">
window.onbeforeunload = bUnload;
function bUnload() {
event.cancelBubble = true;
}
</script>

But still i am not able to prevent the window from closing. I use IE 6.

Regards,
Arun
Arun
Wednesday, 19 September 2007 23:04:58 (GMT Daylight Time, UTC+01:00)
hi arun. the problem there is that your code is permitting the event to cancel itself, allowing the user to exit the page.
if you want to stop the user leaving the page, you must return a string which goes into the popup window. if you replace your event.cancelBubble code with the following code: return "Don't go away"; then it should work for you.
the reason i wrote the article was because you will probably need some way of letting the user leave the page. i use the postback variable to achieve this.
hope this helps
tim
tim
Friday, 28 September 2007 23:40:22 (GMT Daylight Time, UTC+01:00)
So Tim, If a user has pressed save, you simply close the window without any message and complete the unload. What Arun is looking for is a way to cancel the unload and stay on the same page.
marcel
Saturday, 29 September 2007 09:03:07 (GMT Daylight Time, UTC+01:00)
hi marcel. what arun was actually looking for was a way to prevent the user leaving the page AND prevent the dialog from displaying. this is not possible (for good reason). you can't stop a user closing their browser, but browsers do provide this event to give developers the opportunity to at least require a confirmation prompt from the user that they really do want to leave the page. arun's only option is to use the browser prompt to keep users on the page if they try and navigate away (or close the window). the user can click 'cancel' to the prompt which will keep them on the page.
i use the event when a user is editing a page in a CMS that uses a locking mechanism to prevent concurrent edits. the save or cancel buttons are both configured to remove the prompt/event and allow the postback. any other action by the user will display the prompt because the app needs to know whether to release the lock or not. it works the way i want it to anyway.
tim
Wednesday, 02 January 2008 20:47:32 (GMT Standard Time, UTC+00:00)
Hi ,

I want to capture the cancel option . If the user clicks on the cancel button , i need to perform some operations . How can i achieve that ?

Thanks
Anand
ANAND
Wednesday, 02 January 2008 21:11:09 (GMT Standard Time, UTC+00:00)
hi anand. you could try adding a second event handler to the event. hopefully the first one will prompt the user to OK or Cancel the unload, and then your next handler can take effect.
if this doesn't work the newsgroups will be your best bet. good luck.
tim
tim
Wednesday, 25 June 2008 20:07:23 (GMT Daylight Time, UTC+01:00)
Hi Tim,

Excellent article. I've been trying to make this work, however, and no luck. I tried doing it as you did, using an ajax page. Am I doing something wrong?

protected void Page_Load(object sender, EventArgs e)
{
InjectCode();
}

private void InjectCode()
{
Page.ClientScript.RegisterStartupScript(
typeof(String), "ConfirmClose",
@"
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(postback == true)
event.cancelBubble = true;
else
return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";
}
</script>", true);
}
Juan Cabrera
Thursday, 26 June 2008 18:25:50 (GMT Daylight Time, UTC+01:00)
Hi Juan,
did you use the code on your submit button?
OnClientClick="postback=true;return true;"

It sounds like you'll have to do some javascript debugging to figure out why it isn't working. There may be some reason why it wouldn't work with whatever AJAX scripts you have running on the page as well.

Good luck
Tim
tim mackey
Tuesday, 29 July 2008 12:29:11 (GMT Daylight Time, UTC+01:00)
Hi Tim,

your code is working, but not for the reason you believe. This event doesn't bubble.

The "event.cancelBubble" is useless, try without.

Simply it works because you do not return anything in case of "postback == true", and this is the right response to your previous question. The "onbeforeunload=null" is one of the two way, the other is to return "nothing".

Regards,
Orso
Orso
Tuesday, 21 October 2008 23:03:32 (GMT Daylight Time, UTC+01:00)
Worked for me.

Thanks,
Adam Z
Adam Z
Friday, 13 November 2009 15:11:46 (GMT Standard Time, UTC+00:00)
Tim --

This is great, but I was getting an JavaScript error, something like "postback is not defined".

I made it into a static utility helper method, which I will try to post next.

Thank you.

-- Mark Kamoski
Mark Kamoski
Friday, 13 November 2009 15:39:14 (GMT Standard Time, UTC+00:00)
public static void SetExitConfirmation(
System.Web.UI.Page targetPage,
System.Web.UI.WebControls.Button targetSaveButton,
string targetMessage)
{
if (targetPage == null)
{
throw new System.ApplicationException("The given object, targetPage, is null.");
}

if (targetSaveButton == null)
{
throw new System.ApplicationException("The given object, targetSaveButton, is null.");
}

targetMessage = (targetMessage + "").Trim();

targetSaveButton.OnClientClick = "postback=true;return true;";
Type myScriptType = typeof(string);
const string myScriptKey = "ConfirmClose_edede509_7c14_4d33_bf56_0ffee7ca2ea5";

if (!targetPage.ClientScript.IsStartupScriptRegistered(myScriptType, myScriptKey))
{
string myScriptCode = " " +
" <script> " +
" var postback = false; " +
" window.onbeforeunload = ConfirmExit; " +
" " +
" function ConfirmExit() " +
" { " +
" if (postback == false) " +
" { " +
" return '" + targetMessage + "'; " +
" } " +
" } " +
" </script> " +
" ";

targetPage.ClientScript.RegisterStartupScript(myScriptType, myScriptKey, myScriptCode);
}
}
Mark Kamoski
Thursday, 08 April 2010 15:45:32 (GMT Daylight Time, UTC+01:00)
this event doesn't bubble. you can simply use exit() in the event code if you don't want to display the popup, even simpler just don't return anything. The real question is how to if user clicks ...
qba
Thursday, 08 April 2010 15:46:18 (GMT Daylight Time, UTC+01:00)
catch if user clicks cancel or ok...
qba
Tuesday, 09 November 2010 11:26:44 (GMT Standard Time, UTC+00:00)
window.onbeforeunload = function saveBeforeExit(evt) {
if (isFavChanged == 'true') {
return "----------SAVE CHANGES BEFORE EXIT?----------\r\n\r\nOK: Exit without saving...\r\nCANCEL: Return Page in order to Save Changes...";
} else {}
}
Thursday, 19 May 2011 01:51:20 (GMT Daylight Time, UTC+01:00)
I don't mind being warned in a text document but having to close a web browser in order to escape and losing multiple tabs with research for that session is a pain. Most of us should have the option to leave the page without having to click a popup. I'd suggest for an in house page use it as is. But for a web page a second click on the X means goodbye cya ain't coming back. PERIOD.

I usually block those pages so they'll never be visited again. I can find the information I wanted somewhere else. So for friendly use stick to in-house pages.
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview