Handle user close browser event with JavaScript

Published on 17 April 2020

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