Last Updated : 11 Jul, 2025
The onbeforeunload event runs when the document is about to be unloaded, thus, allowing to display message in a dialog box to inform the user whether a user wants to stay or leave the current page, i.e., this event triggers just before a user leaves a webpage, and helps to prevent an accidental closures and retaining unsaved changes. The message rendered will be different for different browsers.
Supported Tags Syntax<element onbeforeunload = "script">Attribute Value
This attribute contains a single value script and it runs when onbeforeunload event is called. This event attribute is supported by <body> tag.
Example: In this example, we will implement the HTML onbeforeunload Event Attribute to trigger the alert message.
html
<!DOCTYPE html>
<html>
<head>
<title>onbeforeunload attribute</title>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
a {
text-decoration: none;
font-weight: bold;
}
</style>
</head>
<body onbeforeunload="return myFunction()">
<h1>
GeeksforGeeks
</h1>
<h2>
onbeforeunload attribute
</h2>
<a href="https://www.geeksforgeeks.org/">
Go to GeeksforGeeks
</a>
<script>
function myFunction() {
return "This document is ready to load";
}
</script>
</body>
</html>
Output:
Supported BrowsersThe browser supported by onbeforeunload attribute are listed below:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4