onbeforeunload event
Definition and usage
The onbeforeunload event occurs when the document is about to be unloaded.
This event allows you to display a message in the confirmation dialog box to notify the user whether to stay or leave the current page.
The default message that appears in the confirmation box varies between different browsers. However, the standard message is similar to "Are you sure you want to leave this page?". This message cannot be deleted.
However, you can write the custom message along with the default message. See the first example on this page. Note: This applies only to Internet Explorer.
Note:If the onbeforeunload event is not assigned to the <body> element, it must be assigned/attached to the window object and a custom message must be created using the returnValue property (see the syntax example below).
Example
Execute JavaScript when the page is about to be unloaded:
<body onbeforeunload="return myFunction()">
Syntax
In HTML:
<element onbeforeunload="myScript">
In JavaScript:
object.onbeforeunload = function(){myScript};
In JavaScript, use the addEventListener() method:
object.addEventListener("beforeunload", myScript);
Note:Internet Explorer 8 or earlier versions do not support addEventListener() method.
Technical details
Bubbling: | Not supported |
---|---|
Cancellable: | Support |
Event type: | If generated from the user interfaceUiEventOtherwise Event. |
Supported HTML Tags: | <body> |
DOM Version: | Level 2 Events |
Browser Support
The numbers in the table indicate the first browser version that fully supports the event.
Events | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onbeforeunload | Support | Support | Support | Support | 15.0 |