onbeforeunloadEvent

事件对象参考手册Event Object

Example

Execute JavaScript when about to leave the current page (refresh or close):

<body onbeforeunload="return myFunction()">

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:

<element onbeforeunload="myScript">Try it yourself

In JavaScript:

object.onbeforeunload=function(){myScript};Try it yourself

In JavaScript, using the addEventListener() method:

object.addEventListener("beforeunload", myScript);Try it yourself

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