HTML onunload Attribute

HTML onunload Attribute: This attribute is defined as it fires once a page has unloaded. Onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.)



HTML onunload Attribute

This attribute can be applied to the <body> element.

Attribute Value

This attribute contains a single value script which works when the onunload event triggered.

Syntax: <body onunload=”script”>

Browser Support

This attribute is supported by the following browsers:

  • Chrome
  • Firefox
  • Internet Explorer
  • Safari
  • Opera

Example: for executing a JavaScript when a user unloads the document

<!DOCTYPE html>
<html>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<script>
function myFunction() {
  alert("Thank you for visiting freshersnow!");
}
</script>

</body>
</html>

Output:

Welcome to my Home Page

Close this window or press F5 to reload the page.

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