onbeforeunload event (Internet Explorer)

Switch View :
ScriptFree
onbeforeunload event

[This documentation is preliminary and is subject to change.]

Fires prior to a document being unloaded.

Syntax

HTML Attribute <element onbeforeunload = "handler(event)">
Event Property object.onbeforeunload = handler;
attachEvent Method object.attachEvent("onbeforeunload", handler)
addEventListener Method object.addEventListener("beforeunload", handler, useCapture)

Standards information

There are no standards that apply here.

Event information

SynchronousNo
BubblesNo
CancelableNo

Event handler parameters

pEvtObj [in]

Type: IHTMLEventObj

Remarks

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 document 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.

When you assign a string to the returnValue property of window.event and the Windows.ApplicationModel.ApplicationExecutionState is running, a dialog box appears that gives users the option to cancel or continue. 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.

When you return null, false, undefined, or nothing from the returnValue property of this event handler, the WWAHost.exe calls the onunload event handler.

When you return true from the returnValue property of this event handler and the Windows.ApplicationModel.ApplicationExecutionState is running, the WWAHost.exe does not display a prompt to the user. It cancels navigation without calling onunload. Instead, you must provide an alternate user interface (UI) to the user to cancel navigation.

When you return some value from this event handler and the Windows.ApplicationModel.ApplicationExecutionState is notRunning, WWAHost.exe ignores the return value and calls the onunload event handler.

Until the user closes WWAHost.exe, you have complete control over the user experience for navigation.

Signals that the document is about to be unloaded.

To invoke this event, do one of the following:

The pEvtObj parameter is required for the following interfaces:

  • HTMLAnchorEvents2
  • HTMLAreaEvents2
  • HTMLButtonElementEvents2
  • HTMLControlElementEvents2
  • HTMLDocumentEvents2
  • HTMLElementEvents2
  • HTMLFormElementEvents2
  • HTMLImgEvents2
  • HTMLFrameSiteEvents2
  • HTMLInputFileElementEvents2
  • HTMLInputImageEvents2
  • HTMLInputTextElementEvents2
  • HTMLLabelEvents2
  • HTMLLinkElementEvents2
  • HTMLMapEvents2
  • HTMLMarqueeElementEvents2
  • HTMLObjectElementEvents2
  • HTMLOptionButtonElementEvents2
  • HTMLScriptEvents2
  • HTMLSelectElementEvents2
  • HTMLStyleElementEvents2
  • HTMLTableEvents2
  • HTMLTextContainerEvents2
  • HTMLWindowEvents2

Examples

This example uses the onbeforeunload event to ask users whether they want to remain on the current document or navigate to a new URL. When the user clicks on the hyperlink or attempts to close the window, the onbeforeunload event fires on the body and a dialog box displays. If the user chooses OK, the document navigates to the new URL (www.microsoft.com) or closes the window; if the user chooses Cancel, the document remains the same.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onbeforeunload.htm


<HTML>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com">Click here to navigate to 
      www.microsoft.com</a>
</body>
</html>

See also

body
frameSet
window
Reference
onload
onunload
Conceptual
Introduction to Data Binding

 

 

Build date: 3/14/2012

Community Content

eneroth3
BUG

"When you return null, false, undefined, or nothing from the returnValue property of this event handler, the WWAHost.exe calls the onunload event handler."

When I return null in IE8 the box still appears asking me "Are you sure you want to navigate away from this page? null".


Mahesh Kumar Mondal
how I get return value of onbeforeunload alert ?
I want to fire a function depending on which button is pressed, either "Leave page" or "Stay on page". That's why i need to capture return value of this alert
" Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page."

raydaz
Can we set the value of hidden field when onbeforeunload is fired, how ?
<html>
<script>
window.body.onbeforeunload = saveBeforeExit;
function saveBeforeExit()
{

var result=confirm("Navigate away Without saving data?");
if (result==true)
{
//alert(document.frmIndex.hdnState2.value); alerts 'onloadvalue';
document.frmIndex.hdnState2.value ='Yes';
//alert(document.frmIndex.hdnState2.value); alerts 'Yes';
}
else
{
//alert(document.frmIndex.hdnState2.value); alerts 'onloadvalue';
document.frmIndex.hdnState2.value ='No';
//alert(document.frmIndex.hdnState2.value); alerts 'No';
}
return;
}
</script>
<body>
<form name="frmIndex">
<input type="hidden" name="hdnState2" value="onloadvalue">
</form>
</body>
</html>

On server side, For hidden field hdnState2, I am getting value 'onloadvalue'.
I am expecting it to be 'Yes' or 'No'.
Can we set the value of hidden field when onbeforeunload is fired, how ? Is there any problem when we are accessing this on server side , asp or jsp.



to read the updated hiddenfield try to use the logic found here on the hidden field.

http://www.rightincode.com/blogs/rightincode/archive/2008/06/05/asp-net-hiddenfield-web-server-control.aspx

Rajesh_Awate
window.close specific event
Is it possible to get a javascript function called for window close specific. onbeforeunload gets called on page refresh or page change which not required for me. $0Or is there any way to differentitate between page unload and window.close in onbeforeunload event.$0

Thomas Lee
Onbeforeunload gets into an infinite loop
We have a situation with IE8 only where onbeforeunload repeats itself after user presses "cancel".

The problem only happens if the content of the page is dynamically changed. But it doesn't happen as soon as the page is changed. Oonbeforeunload is turned off during dynamic changes.

When a user tries to browse away from the page, the onbeforeunload even kicks in as expected. The user clicks on "cancel" and the onbeforeunload pops right back up. It won't go away unless user presses OK which is too late if the user hasn't saved his changes.

This is definitly a bug in IE8. Other browsers (IE7, IE6, Firefox and Safari) work as expected. In our testing, IE8 showed this behavior about 90% of the time while we tested the same steps.


Westmatrix99
Refresh or close in IE8?

Tested code from weazybird...

In Internet Explorer 8 v8.0.6001.18702
Clicking Warning executes the code as set out
Page refresh executes the code WarnUser
Closing the window executes the code WarnUser

In Firefox 3v3.0.13
Clicking Warning executes the code alert(Hello World!)
Page refresh executes nothing
Closing the window executes nothing

This is built for IE, so force everyone to use IE, (...only joking)


Jorge Ojeda Belmar
Prompt twice, and Error not specified when location.href is used

Besides the problem described by weazybird I'm getting this error: "Error not specified" ("Error no especificado") when the event handler's code contains location.href = www.myserver.com
The trick would be to add try/catch to catch the error in order to avoid showing the error to user.
Greeting,
Jorge


george_5154
Dynamically generated iframes...
The onbeforeunload event, triggers on the main document if you create an iframe or if you use location.replace/assign on that iframe (which I think is an error, because the main document is not being reloaded), I consider this a major problem because the event object does not contain any member that tells you what caused the event to trigger, so you cannot handle it properly. On the other hand if you target a form to the same iframe the onbeforeunload event is not invoked (correct behavior). This behavior is clearly inconsistent.

It seams to me like nobody at Microsoft took the time make sure dynamically generated iframes would work fine, I have found lots of issues relating dynamically created iframes, and those issues affect only Microsoft products, all other browser work perfectly OK, so I hope someone is doing their job this time for the release of IE8.

Rim van Wersch
The onbeforeunload Event and the Anchor Tag revisited

Though weazybird's solution works, it is often an inconvenience to hunt down all links and add the onclick event. The same effect however can be achieved by defining a HTC behavior for links in your stylesheet that hooks the proper events. Instead of the onclick event, we found it useful to use the onMouseDown event to disable warnings and additionally hook the OnMouseOut event to re-enable them.


weazybird
The onbeforeunload Event and the Anchor Tag

The onbeforeunload event is often used to warn a user that they have made changes to a web-based form if that user tries to leave the page without saving the changes. This is problematic for pages that use hyperlinks (the <a> anchor tag) to call client-side javascript, even when that code does not result in the user navigating away from the page.

For example, your page may offer a link that allows the user to manipulate content on the page through javascript and the DOM. Normally, you wouldn't want the user to be prompted because of the onbeforeunload event, but this is exactly what happens because you clicked a link and the IE browser believes you may be navigating away from the page.

You can prevent this from happening by using the onclick event of the anchor tag to prevent the onbeforeunload event from firing (set onbeforeunload = null) or setting a flag to allow the onbeforeunload event to continue without prompting the user.

Consider the following example where the method of setting a temporary flag is used. The flag is reset after a single use so you would need to call "NoPrompt()" from every link where onbeforeunload processing should be disabled.

<html>
<body>
<a href="javascript:alert('Hello World!');">Warning</a><br/>
<a onclick="NoPrompt();" href="javascript:alert('Hello World!');">No Warning</a>
<script>
// Allow the user to be warned by default.
var allowPrompt = true;
window.onbeforeunload = WarnUser;

function WarnUser()
{
if(allowPrompt)
{
event.returnValue = "You have made changes. They will be lost if you continue.";
}
else
{
// Reset the flag to its default value.
allowPrompt = true;
}
}

function NoPrompt()
{
allowPrompt = false;
}
</script>
</body>
</html>