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



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

Supported Tags


Browser compatibility

onbeforeunload Yes Yes Yes Yes Yes


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


Click to view the demo