HTML onbeforeunload attribute

HTML onbeforeunload attribute: This attribute triggers when the document is about to load. This attribute helps the user to make sure that they want to leave this current page or not. The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like “Are you sure you want to leave this page?”. You cannot remove this message.

HTML onbeforeunload attribute

In the attribute, users cannot remove the message but they can add a custom message n the dialog box.  And this attribute is a part of the <body> element. And only in the Firefox, the default message will be displayed.

Syntax: <body onbeforeunload=”script”>



Browser compatibility

This attribute supports different types of browsers as follows:

  • Chrome
  • Mozilla
  • InternetExplorer
  • Safari
  • Opera-15.0

Example:

<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
<a href="https://tutorials.freshersnow.com">Click here to go to tutorials.freshersnow.com</a>
  
<script>
function myFunction() {
  return "Write something clever here...";
}
</script>

</body>
</html>

Output:

Close this window, press F5 or click on the link below to invoke the onbeforeunload event.

Click here to go to tutorials.freshersnow.com