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
Execute a script when the browser window is closed in HTML?
The onunload event attribute in HTML triggers when the browser window is being closed, refreshed, or navigated away from. This event allows you to execute JavaScript code before the page is completely unloaded from memory.
Syntax
Following is the syntax for the onunload attribute −
<body onunload="functionName()">
You can also use addEventListener in JavaScript −
window.addEventListener('unload', function() {
// Your code here
});
Using onunload Attribute
The onunload event fires when the user leaves the page by closing the browser window, clicking a link, refreshing the page, or typing a new URL. This event is commonly used for cleanup tasks like saving data or showing farewell messages.
Example
Following example demonstrates the onunload attribute with an alert message −
<!DOCTYPE html>
<html>
<head>
<title>OnUnload Event Example</title>
</head>
<body onunload="display()" style="font-family: Arial, sans-serif; padding: 20px;">
<h2>TutorialsPoint</h2>
<h3>Simply Easy Learning</h3>
<p>Close this window or refresh the page to see the unload event.</p>
<script>
function display() {
alert("Goodbye! Thanks for visiting TutorialsPoint.");
}
</script>
</body>
</html>
When you close the browser window or navigate away from this page, an alert box will appear with the goodbye message.
Modern Approach with beforeunload
The beforeunload event is more commonly used in modern web development as it allows users to confirm whether they want to leave the page. Unlike onunload, it can potentially prevent the page from closing.
Example
Following example shows how to use the beforeunload event −
<!DOCTYPE html>
<html>
<head>
<title>BeforeUnload Event Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Page with Confirmation Dialog</h2>
<p>Try to close this window or navigate away to see the confirmation dialog.</p>
<input type="text" placeholder="Type something here..." style="padding: 8px; width: 300px;">
<script>
window.addEventListener('beforeunload', function(event) {
event.preventDefault();
event.returnValue = ''; // Required for Chrome
return 'Are you sure you want to leave?';
});
</script>
</body>
</html>
This example shows a confirmation dialog when the user attempts to leave the page, giving them a chance to cancel the action.
addEventListener Method
The modern approach uses addEventListener instead of inline event attributes for better code organization and flexibility.
Example
<!DOCTYPE html>
<html>
<head>
<title>addEventListener Unload Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Modern Unload Event Handling</h2>
<p>This page uses addEventListener for the unload event.</p>
<button onclick="removeListener()">Remove Unload Listener</button>
<script>
function unloadHandler() {
// Note: alert() may not work reliably in unload event
console.log("Page is being unloaded");
}
function removeListener() {
window.removeEventListener('unload', unloadHandler);
alert("Unload listener removed!");
}
// Add the event listener
window.addEventListener('unload', unloadHandler);
</script>
</body>
</html>
This approach allows you to add and remove event listeners dynamically and provides better control over the event handling.
Browser Compatibility and Limitations
The onunload event has some important limitations:
-
Alert restrictions − Many modern browsers block
alert(),confirm(), andprompt()during the unload event for security reasons. -
Timing issues − The unload event happens very late in the page lifecycle, so some operations may not complete.
-
Mobile limitations − Mobile browsers may not always trigger unload events reliably due to background app management.
-
Single-page applications − In SPAs, use framework-specific lifecycle methods instead of window unload events.
Best Practices
When working with unload events, follow these recommendations:
-
Use
beforeunloadfor user confirmations andunloadfor cleanup tasks only. -
Avoid heavy computations or network requests in unload handlers as they may not complete.
-
Use
navigator.sendBeacon()for sending analytics data during page unload. -
Test unload behavior across different browsers and devices for consistent experience.
Conclusion
The onunload attribute allows you to execute JavaScript when a browser window is closed or navigated away from. While useful for cleanup tasks, modern applications typically use beforeunload for user confirmation dialogs and addEventListener for better code organization and reliability.
