Handling Browser Close Events with JavaScript


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.

Here’s what the dialog looks like in Chrome:

And in Firefox:

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.
  event.preventDefault()
  // 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