HTML onbeforeunload Event Attribute


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?"; };


<element onbeforeunload="script">


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


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

Supported Tags


Browser Support

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