onunload event

Definition and usage

The onunload event occurs once the page has been unloaded (or the browser window has been closed).

When the user leaves the page (by clicking a link, submitting a form, closing the browser window, etc.),

Note:When the user reloads the page (and onload Event). Also triggers the onunload event.

Example

Execute JavaScript when the user unloads the document:

<body onunload="myFunction()">

Try it yourself

Syntax

In HTML:

<element onunload="myScript">

Try it yourself

In JavaScript:

object.onunload = function(){myScript};

Try it yourself

In JavaScript, use the addEventListener() method:

object.addEventListener("unload", myScript);

Try it yourself

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

Technical details

Bubble: Not supported
Cancelable: Not supported
Event type: If generated from the user interface,UiEvent. Otherwise Event.
Supported HTML tags: <body>
DOM Version: Level 2 Events

Browser Support

Events Chrome IE Firefox Safari Opera
onunload Support Support Support Support Support

Note:Due to different browser settings, this event may not always work as expected.