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 anEvent
object, there you need to set a truthy value to thereturnValue
property in theEvent
object. In our case, we have set the value of booleantrue
to the propertyreturnValue
.
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! 🔥