Browser Tab Closing Confirmation Using JavaScript

By
coding
javascript
ui/ux
Open in Demo.js

Online web applications, such as document editors and chat apps, have this feature to prevent users from accidentally closing or reloading the browser tab if there is any unsaved content, so they can decide if they want to save it or lose it. Let's see how we can do this using JavaScript.

Check out the following example. Click on the given button and turn on close confirmation. Then try to close or reload this browser tab. And try again after turning it off.

Using the beforeunload event, you can simply create this confirmation prompt. The only thing you have to do is prevent that event by calling the preventDefault method. So, add the event listener and prevent it inside the callback function.

// event listener when browser tab is closing
window.addEventListener("beforeunload", event => {
  // prevent event default behavior
  event.preventDefault()
})

If you implement the above code, you have no control over the confirmation. Sometimes, the user should be able to close the browser without confirmation if they have saved their progress in the web app. We only need to take confirmation from them when they are about to abandon any ongoing work.

Therefore, we have to maintain a Boolean value so we can conditionally call the preventDefault method.

// current locked status
let isLocked = false

// event listener when browser tab is closing
window.addEventListener("beforeunload", event => {
  // prevent event only if locked
  if(isLocked) { event.preventDefault() }
})

And you can switch this isLocked boolean whenever you need. Look at the following example, where we only unlock the status when the file is saved successfully.

// function to save document
function saveDocument() {
  // request file save
  saveFileContent().then(() => {
    // unlock on success
    isLocked = false
  }).catch(() => {
    // do not unlock if failed
    alert("Save Failed!")
  })
}