The unload event in JavaScript is triggered when a page is about to unload or is navigating away.
This event is commonly used to perform cleanup tasks or to prompt the user for confirmation before leaving the page.
The unload event can be handled using the addEventListener method or by assigning a function directly to the onunload property.
Here's an example using addEventListener:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>unload Event Example</title> </head> <body> <script> function handleUnload(event) { // Your cleanup or confirmation logic here const message = 'Are you sure you want to leave this page?'; event.returnValue = message; // Standard for most browsers return message; // For some older browsers } // Attach the unload event listener to the window window.addEventListener('unload', handleUnload); </script> </body> </html>
The handleUnload function contains the logic that should be executed when the page is about to unload.
The event parameter provides information about the event and event.returnValue is set to a confirmation message.
This message will be displayed to the user as a confirmation dialog before leaving the page.
The addEventListener method is used to attach the unload event listener to the window object.
<script> function handleUnload(event) { // Your cleanup or confirmation logic here const message = 'Are you sure you want to leave this page?'; event.returnValue = message; // Standard for most browsers return message; // For some older browsers } // Assign the unload event handler directly to the onunload property window.onunload = handleUnload; </script>
Alternatively, we can use the onunload property directly:
Modern browsers may restrict certain actions in the unload event due to security concerns.
Actions that require user interaction, such as showing a confirmation dialog, are typically allowed.
However, performing asynchronous tasks or making network requests may not be reliable in the unload event