Execute a script when the document is about to be unloaded in HTML?


The onbeforeunload event attribute’ fires when the document is ready to be unloaded.

Example

You can try to run the following code to implement the onbeforeunload attribute −

<!DOCTYPE html>
<html>
   <body onbeforeunload = "return display()">
      <p>Close this window or press F5.</p>
      <script>
         function display() {
            return "Wanna stay here or leave?";
         }
      </script>
   </body>
</html>

Updated on: 03-Mar-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements