onbeforeunload event


onbeforeunload Event

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body onbeforeunload="return myFunction()">

<p>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>
<a href="http://www.w3cschool.cc">点击跳转到w3cschool.cc</a>    
<script>
function myFunction() {
    return "我在这写点东西...";
}
</script>

</body>
</html>

Run Instance»

Click "Run instance" button to view the online instance



Definition and usage

The onbeforeunload event is triggered when the current page is about to be left (refreshed or closed).

This event can be used to pop up a dialog box to prompt the user whether to continue browsing the page or leave the current page.

The default prompt message of the dialog box varies according to different browsers. The standard message is similar to "Are you sure you want to leave this page?". This information cannot be deleted.

But you can customize some message prompts to be displayed in the dialog box together with the standard information.

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 returnValue Properties create custom information (see below for syntax examples).

Note: In the Firefox browser, only the default reminder information is displayed (customized information is not displayed).


Browser support

The number in the table indicates the version number of the first browser that supports the event.

4.png

Syntax

HTML:

<element onbeforeunload="myScript ">Try it

In JavaScript:

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

In JavaScript, use the addEventListener() method:

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

Note: Internet Explorer 8 and earlier IE versions do not support the addEventListener() method.


Technical details##Supported HTML tags: <body>
Whether bubbling is supported:No
Can be canceled:Yes
Event type:Event