Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

onbeforeunload event

onbeforeunload event

Event Object Reference Event Object

Example

Execute JavaScript when about to leave the current page (refresh or close):

<body onbeforeunload=">

return myFunction()

"

Try it »


Definition and Usage

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

This event can be used to pop up a dialog prompting the user whether to continue browsing the page or leave the current page.

The default prompt message of the dialog varies by browser; a standard message is similar to "Are you sure you want to leave this page?" This message cannot be removed.

But you can customize some messages to be displayed together with the standard message in the dialog.

Note: If you do not specify the onbeforeunload event on the element, you need to add the event on the window object and use the returnValue property to create custom information (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 version number of the first browser to support the event.

Events
onbeforeunload Yes Yes Yes Yes 15.0

Syntax

In HTML:

<

element

onbeforeunload="

myScript

">

Try it

In JavaScript:

object

.onbeforeunload=function(){

myScript

};

Try it

In JavaScript, use the addEventListener() method:

object

.addEventListener("beforeunload",

myScript

);

Try it

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


Technical Details

Does it support bubbling: No
Is it cancelable: Yes
Event type: Event
Supported HTML tags:  

Event Object Reference Event Object