# How to detect browser or tab closing in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 24, 2022, updated Sep 10, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-detect-browser-tab-closing

> A quick guide to learning how to detect browser or tab closing using JavaScript.

In JavaScript, you can use the `beforeunload` event to detect a tab or window closing in a browser. It is used to alert the user about unsaved changes on the webpage or to prevent the user from mistakenly closing the window or the browser.

Here is an example that you can use to display an alert message when the user tries to close a tab or window:

```javascript
window.addEventListener('beforeunload', (e) => {
  e.preventDefault()
  return (e.returnValue = 'Are you sure you want to close?')
})
```

We use the `addEventListener()` method to [attach an event handler](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) to any [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript) object including HTML elements, `document` object, and `window` object.

The `beforeunload` is fired right before the window, the document, and its resources are about to be unloaded. At this point, the document is still visible, and the event is still cancelable.

According to the specification, you must call `preventDefault()` on the event to show the confirmation dialog. The `preventDefault()` method is used to [prevent default action of an event](https://attacomsian.com/blog/javascript-dom-prevent-default-action-of-an-event). In this case, the unloading of resources, the window, and the document.

Note that some browsers may not display prompts created in `beforeunload` event handlers unless the user has interacted with the page. This is used to combat unwanted pop-ups created by malicious websites.
