To detect a browser or tab close event in JavaScript:
- Add a
beforeunload
event listener to the globalwindow
object. - In this listener, call the
preventDefault()
method on theEvent
object passed to it. - Set the
returnValue
property of thisEvent
object to an empty string (''
).
JavaScript
window.addEventListener('beforeunload', (event) => {
event.preventDefault();
event.returnValue = '';
});
We’ll need to detect the event of a browser or tab close to alert the user of any unsaved changes on the webpage.
We use the addEventListener()
method to attach an event handler to any DOM objects such as HTML elements, the HTML document
, or the window
object.
The beforeunload
event is fired right before the window, document, and its resources are about to be unloaded. At this point, the document is still visible, and the event is still cancelable.
We have to call preventDefault()
on the Event
object the handler receives to show the confirmation dialog in the browser. The preventDefault()
method prevents the default action of an event. For the beforeunload
event, preventDefault()
stops the unloading of the resources, the window, and the document.
This JavaScript code will cause a confirmation dialog to be displayed when the user tries to close the browser or tab. Here’s some sample HTML to use the JavaScript in.
HTML
<a href="codingbeautydev.com">Coding Beauty</a>
<br />
Try to close the tab or browser
Note that the beforeunload
event is triggered not only when the browser or tab is closed, but also when a link is clicked, a form is submitted, the backward/forward button is pressed, or the page is refreshed.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.