JavaScript beforeunload Event
Summary: in this tutorial, you will learn about the JavaScript beforeunload
event that allows you to display a confirmation dialog when before you leave a webpage.
Introduction to JavaScript beforeunload
event
Before the webpage and its resources are unloaded, the beforeunload
event is fired. At this time, the webpage is still visible and you have an opportunity to cancel the event.
To register for the beforeunload
event, you use the window.addEventListener()
method:
window.addEventListener('beforeunload',(event) =>{
// do something here
});
Code language: JavaScript (javascript)
Since the window
is the global object, you can omit it like this:
addEventListener('beforeunload',(event) =>{
// do something here
});
Code language: PHP (php)
If a webpage has a beforeunload
event listener and you are about to leave the page, the beforeunload
event will trigger a confirmation dialog to confirm if you really want to leave the page.
If you confirm, the browser navigates you to the new page. Otherwise, it cancels the navigation.
According to the specification, you need to call the preventDefault()
method inside the beforeunload
event handler in order to show the confirmation dialog. However, not all browsers implement this:
addEventListener('beforeunload',(event) => {
event.preventDefault();
});
Code language: PHP (php)
Historically, some browsers allow you to display a custom message on the confirmation dialog. This was intended to inform the users that they will lose data if they navigate away. Unfortunately, this feature is often used to scam users. As a result, a custom message is no longer supported.
Based on the HTML specification, the calls to alert()
, confirm()
, and prompt()
are ignored in the beforeunload
event handler.
JavaScript beforeunload
event example
The following example attaches an event handler to the beforeunload
event. If you click the link to navigate to another page, the browser will show a confirmation dialog.
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS beforeunload Event</title>
</head>
<body>
<a href="https://www.javascripttutorial.net/">JavaScript Tutorial</a>
<script>
window.addEventListener('beforeunload', (event) => {
event.preventDefault();
// Google Chrome requires returnValue to be set.
event.returnValue = '';
});
</script>
</body>
</html>
Code language: HTML, XML (xml)
Summary
- The
beforeunload
event is fired before the webpage and its resources are about to unload. - Use
beforeunload
to confirm if users really want to leave the page to prevent data loss.