onbeforeunloadEvent
Example
Execute JavaScript when about to leave the current page (refresh or close):
Try it yourself »
Definition and Usage
The onbeforeunload event is triggered when about to leave the current page (refresh or close).
This event can be used to pop up a dialog box, prompting the user whether to continue browsing the page or leave the current page.
The default prompt message in the dialog box varies depending on the browser. The standard message is similar to "Are you sure you want to leave this page?". This message cannot be removed.
But you can customize some message prompts to be displayed together with the standard message in the dialog box.
Note:If you do not specify the onbeforeunload event on the <body> element, you need to add the event on the window object and use the returnValue property to create custom information (see the syntax examples below).
Note:In Firefox browser, only the default reminder message is displayed (custom information is not displayed).
Browser Support
The numbers in the table indicate the version number of the first browser that supports the event.
| Event | |||||
|---|---|---|---|---|---|
| onbeforeunload | Yes | Yes | Yes | Yes | 15.0 |
Syntax
In HTML:
In JavaScript:
In JavaScript, using the addEventListener() method:
Note:Internet Explorer 8 and earlier IE versions do not supportaddEventListener()the method.
Technical Details
| Does it support bubbling: | No |
|---|---|
| Is it cancellable: | Yes |
| Event type: | Event |
| Supported HTML tags: | <body> |
Event Object Other extensions