HTML event attribute onbeforeunload








The onbeforeunload event is triggered before the HTML document is unloaded.

We can use this event display a message to inform the user of leaving.

There is a default message appearing in the confirmation dialog. You cannot overwrite this message.

We can add our own message if necessary.

What's new in HTML5

None.

Syntax

<element onbeforeunload="script or javascript function name">

Supported Tags

<body>

Browser compatibility

onbeforeunload Yes Yes Yes Yes Yes




Example

<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">
<!--from  w w  w .  jav  a 2  s. c  o  m-->
<a href="http://www.java2s.com">Click here to see the dialog.</a>
      
<script>
function myFunction() {
    return "hi";
}
</script>

</body>
</html>

Click to view the demo