HTML onbeforeunload Event Attribute

HTML onbeforeunload Event Attribute

❮ HTML Event Attributes


Execute a JavaScript when the page is about to be unloaded:

<body onbeforeunload="return myFunction()">
Try it Yourself »

Definition and Usage

The onbeforeunload event fires when the document is about to be unloaded.

This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.

The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like "Are you sure you want to leave this page?". You cannot remove this message.

However, you can write a custom message together with the default message. See the first example on this page.

Note: In Firefox, only the default message will be displayed (not the custom message (if any)).

Browser Support

The numbers in the table specify the first browser version that fully supports the event.

Event Attribute
onbeforeunload Yes Yes Yes Yes 15.0

Differences Between HTML 4.01 and HTML5



<element onbeforeunload="script">

Attribute Values

Value Description
script The script to be run on onbeforeunload

Technical Details

Supported HTML tags: <body>

Related Pages

HTML DOM reference: onbeforeunload event

❮ HTML Event Attributes