Open In App

HTML onbeforeunload Event Attribute

Improve
Improve
Like Article
Like
Save
Share
Report

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>
        Go to GeeksforGeeks
    </a>
    <script>
        function myFunction() {
            return "This document is ready to load";
        }
    </script>
</body>
 
</html>


Output:

qw

Supported Browsers

The browser supported by onbeforeunload attribute are listed below: 

  • Google Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Opera 15 and above
  • Safari 3 and above


Last Updated : 13 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads