Handle user close browser event with JavaScript

April 17, 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:

ff705 screenshot 2020 04 17 at 12 43 18 am

For Firefox, it looks like this:

70fdb screenshot 2020 04 17 at 12 42 43 am

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.
              // 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

Profile picture

Experience in software development, application architecture, and deploying cloud solutions for enterprise customers. Strong hands-on skills with a Master's degree in Computer Science and business acumen with a master of business administration (MBA) in Finance. Certified in Amazon Web Services (AWS), Google Cloud Platform (GCP), Microsoft Azure, Kubernetes (CKA, CKAD, CKS, KCNA) and Scrum (PSM, PSPO) with experience in building banking products from scratch. Connect on Linkedin

© 2022, @victorleungtw