Showing alert popup while user closing the tab in the browser

You might have seen a confirmation popup while closing the browser tab in several web apps. Especially when you are discarding the drafts and leave the page. Do you know how to achieve that in JavaScript?

It is very easy, we need to create a overwrite onbeforeunload window method. This method gets called before the browser window fires the unload method,

window.onbeforeunload = function (e) {
  return false;

You need to return some value. Then automatically, it will show a default alert popup with a confirmation message.

Changes that you made may not be saved.

You can check out the example here. Open the codesandbox example in a new tab and try closing the tab. You will see the popup. It is supported in all major browsers.