Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the usage of onunload event in JavaScript?
The onunload event triggers when a user navigates away from a page, closes the browser tab, or refreshes the page. This event is useful for cleanup tasks like saving user data or showing farewell messages.
Syntax
// HTML attribute
<body onunload="functionName()">
// JavaScript event listener
window.addEventListener('unload', function(event) {
// Cleanup code
});
Example: Using onunload with HTML Attribute
<!DOCTYPE html>
<html>
<body onunload="newFunc()">
<p>Close the page and see what happens!</p>
<p>This event may give unexpected results in some browsers.</p>
<script>
function newFunc() {
alert("Thank you for visiting!");
}
</script>
</body>
</html>
Example: Using addEventListener (Modern Approach)
<!DOCTYPE html>
<html>
<body>
<p>Navigate away from this page to trigger the unload event.</p>
<script>
window.addEventListener('unload', function(event) {
// Save data before leaving
localStorage.setItem('lastVisit', new Date().toISOString());
});
</script>
</body>
</html>
Browser Compatibility and Limitations
Modern browsers have restricted the onunload event for security reasons. Many browsers now ignore alert(), confirm(), or prompt() calls during unload. Consider using beforeunload for user confirmations instead.
Alternative: beforeunload Event
<script>
window.addEventListener('beforeunload', function(event) {
event.preventDefault();
event.returnValue = ''; // Shows browser's default confirmation dialog
});
</script>
Common Use Cases
- Saving form data to localStorage
- Logging analytics events
- Cleaning up resources like timers or connections
- Sending final data to server (use navigator.sendBeacon)
Conclusion
The onunload event is useful for cleanup tasks when users leave a page. However, modern browsers limit its functionality, so consider beforeunload for user confirmations and keep unload handlers lightweight.
Advertisements
