To add a confirmation before the closing of the tab/browser with JavaScript, we set the window.onbeforeunload
property to a function that shows the alert.
For instance, we write
window.onbeforeunload = (e) => {
return "Sure?";
};
to set window.onbeforeunload
to a function that returns a non-empty string.
Then the browser will show an alert box before we close the tab or browser window.