Fires prior to a document being unloaded.
Syntax
| HTML Attribute | <element onbeforeunload = "handler(event)"> |
|---|---|
| Event Property | object.onbeforeunload = handler; |
| addEventListener Method | object.addEventListener("beforeunload", handler, useCapture) |
Event information
| Synchronous | No |
|---|---|
| Bubbles | No |
| Cancelable | No |
Event handler parameters
- pEvtObj [in]
-
Type: IHTMLEventObj
Standards information
There are no standards that apply here.
Remarks
onbeforeunload in Windows Store apps using JavaScript
In Windows Store apps using JavaScript, the onbeforeunload event fires before the top-level page in navigated. The returnValue property of window.event is always ignored and onunload will fire immediately. No dialog is shown to the user and the navigation can't be cancelled. Note that, in most cases, the app should never navigate its top-level document. Windows Store apps using JavaScript should use oncheckpoint event to determine when they need to save state information.
General info
This event signals that the document is about to be unloaded.
To invoke this event, do one of the following:
- Close the current window.
- Navigate to another location by entering a new address or selecting a Favorite.
- Click an anchor that refers to another document.
- Invoke the anchor.click method.
- Invoke the document.write method.
- Invoke the document.close method.
- Invoke the window.close method.
- Invoke the window.navigate or NavigateAndFind method.
- Invoke the location.replace method.
- Invoke the location.reload method.
- Specify a new value for the location.href property.
- Submit a form to the address specified in the ACTION attribute via the INPUT type=submit control, or invoke the form.submit method.
- Invoke the window.open method, providing the possible value _self for the window name.
- Invoke the document.open method.
- Click the Back, Forward, Refresh, or Home button.
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
<!DOCTYPE html>
<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
- window
- Reference
- onload
- onunload
- Conceptual
- Introduction to Data Binding
Send comments about this topic to Microsoft
Build date: 11/29/2012