How to detect browser or tab closing in 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:

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

We use the addEventListener() method to attach an event handler to any DOM 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. 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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.