Handle user close browser event with JavaScript

For some scenarios, you don’t want the user to close the browser and exit the journey. For example, if a user is filling in a form without saving or in the middle of payment transaction without complete, then you could prompt the user with confirmation dialog when the user clicks the close browser button.

For Chrome, it looks like this:

For Firefox, it looks like this:

This can be achieved via the beforeunload event in the browser, add this Javascript code to your page:


        window.addEventListener('beforeunload', (event) => {
          // Cancel the event as stated by the standard.
          event.preventDefault();
          // Chrome requires returnValue to be set.
          event.returnValue = '';
        });

Notice that in order to trigger this event, the user needs to have some interaction with the page. Otherwise, this would not be able to trigger. Besides, they would trigger in the below three scenarios:

1. User clicks to close the browser.
2. User clicks to refresh the page.
3. User clicks on the back button.

If you wish to remove this confirmation dialog, such as after the user save the form or completed the payment transactions, you could remove it like this:


  window.removeEventListener("beforeunload", callback)

Since the primary purpose of this dialog is to remind users to save changes before their changes are lost, there is no further event listener to capture the result of this exit dialog, i.e. you can’t do anything to find out if the user further proceed with leave button or the stay button that the user clicked on.

For more information, check out the latest MDN web docs here: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.