How to show a 'Are you sure to leave?', 'Leave Site?', etc. dialog box in the browser before the user leaves using JavaScript?

April 8, 2021 - 2 min read

To show 'Are you sure you want to leave?', 'Leave Site' or to show the dialog box which gives attention to the user when he/she closes the browser or reloads a tab, you can attach an event listener called beforeunload to the global window object using JavaScript.

It can be done like this,

// Show "Leave Site?" Dialog Box

window.addEventListener("beforeunload", (event) => {
  // set a truthy value to property returnValue
  event.returnValue = true;
});
  • The callback function in the addEventListener function will be passed an Event object, there you need to set a truthy value to the returnValue property in the Event object. In our case, we have set the value of boolean true to the property returnValue.

It would show a dialog box when the user leaves the browser like this,

There is one more way you can do the same thing by directly attaching the onbeforeunload function which returns a truthy value to the global window object like this,

/* Show "Are you sure to leave?" Dialog Box */

// Alternate Way of doing same thing
window.onbeforeunload = () => {
  return true;
};

That's all! 🔥

Feel free to share if you found this useful 😃.