How to Detect a Browser or Tab Close Event in JavaScript

Last updated on November 25, 2022
How to Detect a Browser or Tab Close Event in JavaScript

To detect a browser or tab close event in JavaScript:

  1. Add a beforeunload event listener to the global window object.
  2. In this listener, call the preventDefault() method on the Event object passed to it.
  3. Set the returnValue property of this Event 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="wp.codingbeautydev.com">Coding Beauty</a>
<br />
Try to close the tab or browser
A confirmation dialog is shown when the user tries to close the tab.
A confirmation dialog is shown when the user tries to close the tab.
A confirmation dialog is shown when the user tries to close the browser.
A confirmation dialog is shown when the user tries to close the 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.

A confirmation dialog is shown when a link is clicked on the page.
A confirmation dialog is shown when a link is clicked on the page.
A confirmation dialog is shown when the user tries to refresh the page.
A confirmation dialog is shown when the user tries to refresh the page.
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also