JavaScript beforeunload
The beforeunload
event is fired by the window object when the user is leaving the page. The purpose of the event is to give developers a chance to save data or prompt the user with a warning message before the page is unloaded.
Syntax
window.addEventListener('beforeunload', function(event) {
// your code here
});
Example
<!DOCTYPE html>
<html>
<head>
<title>beforeunload Example</title>
</head>
<body>
<h1>Beforeunload Example</h1>
<form>
<input type="text" name="inputField">
</form>
<script>
window.addEventListener('beforeunload', function(event) {
event.preventDefault();
event.returnValue = '';
});
</script>
</body>
</html>
Output
When the user tries to leave the page by closing the tab or the whole browser window, a confirmation dialog will appear with a message of your choosing. If you click "Stay on this page", the page will not unload.
Explanation
The beforeunload
event is fired on the window
object when the user is about to leave the page. We can attach an event listener to the window
object that will listen to this event and perform an action when it is fired. In this case, we're preventing the default behaviour of the event (unloading the page), and setting the returnValue
property of the event object to an empty string. This prompts the user with a confirmation dialog with a generic message asking if they want to leave the page and the text "(Changes you made may not be saved)".
Use
The beforeunload
event can be useful when you want to give the user a chance to save their work, or when you need to prevent them from accidentally leaving the page with unsaved changes.
Important Points
- The
beforeunload
event is fired on thewindow
object when the user is about to leave the page. - We can attach an event listener to the
window
object that will listen to this event and perform an action when it is fired. - The
returnValue
property of the event object is used to set the message displayed to the user in the confirmation dialog. - The beforeunload event does not work on mobile browsers.
Summary
The beforeunload
event gives developers a chance to save data or prompt the user with a warning message before the page is unloaded. It can be useful when you want to prevent the user from leaving the page with unsaved data or when you need to give them a chance to save their work.