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="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.



11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.


Leave a Comment

Your email address will not be published. Required fields are marked *