DEV Community

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

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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;
});
Enter fullscreen mode Exit fullscreen mode
  • 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,

dialog-box-shown-in-browser

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;
};
Enter fullscreen mode Exit fullscreen mode

That's all! 🔥

Feel free to share if you found this useful 😃.


Top comments (1)

Collapse
 
sancho1952007 profile image
Sancho Godinho

Thank you so much bro!