``` --- ## Definition and Usage"> ``` --- ## Definition and Usage" />
Easy Tutorial
❮ Prop Canvas Shadowoffsety Jsref Regexp Whitespace Non ❯

onbeforeunload Event

Event Object

Example

Execute JavaScript when leaving the current page (refresh or close):

<body onbeforeunload="return myFunction()">

Definition and Usage

The onbeforeunload event is triggered when the page is about to be unloaded (refresh or close).

This event can be used to display a dialog box asking the user whether to stay on the page or leave.

The default message in the dialog box varies by browser, typically something like "Are you sure you want to leave this page?". This default message cannot be removed.

However, you can customize additional messages to be displayed alongside the default message.

Note: If you do not specify the onbeforeunload event on the <body> element, you need to add the event to the window object and use the returnValue property to create a custom message (see the syntax example below).

Note: In Firefox, only the default alert message is displayed (custom messages are not shown).


Browser Support

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

Event
onbeforeunload Yes Yes Yes Yes 15.0

Syntax

In HTML:

In JavaScript:

In JavaScript, using the addEventListener() method:

Note: Internet Explorer 8 and earlier versions do not support the addEventListener() method.


Bubbles: No
Cancelable: Yes
--- ---
Event Type: Event
--- ---
Supported HTML Tags: <body>
--- ---
❮ Prop Canvas Shadowoffsety Jsref Regexp Whitespace Non ❯