Handling Browser Close Events with JavaScript

April 17, 2020

In certain scenarios, you may not want users to close their browser and exit the session. For instance, if a user is in the middle of filling out a form without saving, or in the midst of a payment transaction that hasn't been completed, you could prompt the user with a confirmation dialog when they attempt to close the browser.

2020 04 17

Here's what the dialog looks like in Chrome:

ff705 screenshot 2020 04 17 at 12 43 18 am

And in Firefox:

70fdb screenshot 2020 04 17 at 12 42 43 am

This functionality can be implemented by using the beforeunload event in JavaScript. Add the following code to your web page:

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

Note that this event will only trigger if the user has had some interaction with the page. Otherwise, it won't activate. Additionally, the event will be triggered in the following three scenarios:

  1. The user clicks to close the browser.
  2. The user clicks to refresh the page.
  3. The user clicks the back button.

If you want to remove this confirmation dialog, perhaps after the user has saved the form or completed the payment transaction, you can do so like this:

window.removeEventListener('beforeunload', callback);

Since the primary purpose of this dialog is to remind users to save their changes before leaving, there is no additional event listener to capture the result of the exit dialog. In other words, you can't determine whether the user chose to leave or stay on the page.

For more information, you can consult the latest MDN Web Docs here: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

Profile picture

Victor Leung, who blog about business, technology and personal development. Happy to connect on LinkedIn