HTML onbeforeunload Event Attribute

Description

The event attribute onbeforeunload is triggered if a visitor initiated a transition to another page or clicked "close window". This event allows you to pause the process and ask for confirmation.

The default message displayed in the dialog box is different in different browsers. However, it will be something like this: "Do you really want to leave this page?" ("Are you sure you want to leave this page?"). This message cannot be changed or deleted, but we can add our custom message in the dialog box.

For example:

onbeforeunload = function() { return "Save data before exit?"; };

Syntax

<element onbeforeunload="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Event attribute onbeforeunload</title>
</head>
<body onbeforeunload="myFunction()">
<p>Close this window, press F5 or click on the link below to trigger an event for onbeforeunload.</p>
<a href="https://www.cssportal.com">Go to CSSPortal.com</a>
<script>
function myFunction() {
    return "Are you sure you want to leave this page?";
}
</script>
</body>
</html>

Supported Tags

<body>

Browser Support

Desktop
Explorer Edge Chrome Firefox Opera Safari
??????
Tablets / Mobile
Android Chrome Firefox Opera Safari Samsung
??????