-3

I want to show a dialog when users click the X button to close the browser's window. In the dialog, it will ask users if they want to proceed with closing or not, if users choose no, it won't close the window.

I am wondering how to achieve this. I tried the unload event handler, the code was triggered but the window has already been closed. I also tried onbeforeunload, but it seems not triggered at all.

window.addEventListener('onbeforeunload ', () => {
   // code not triggered here
});

window.addEventListener('unload', () => {
   // code triggered but window is already closed
});

Even if we assume that there is an event handler which will be triggered before the window is closed, then what code should I write in order to prevent closing the window? It looks like once X button is clicked, the window is just "determined" to close and it's not reversible?

flyingbee
  • 601
  • 1
  • 7
  • 17

1 Answers1

1

[https://stackoverflow.com/questions/2923139/prompt-user-before-browser-close]

this is the basic way to do but prompt will be always the same

window.onbeforeunload = function(evt) {
   return true;
}
Vaisakh K M
  • 105
  • 1
  • 7
  • I see...so I guess there is no way to have a customized dialog where we can click a button to stop browser from closing the window? – flyingbee May 13 '22 at 04:19
  • @flyingbee i guess not.. but i am not experinced enough... – Vaisakh K M Jun 03 '22 at 18:28
  • @flyingbee No, there is no way to customize the message. You also can't force the prompt to show if the user made "no meaningful interaction" beforehand, or if you showed "too many" prompts (browser dependent). The reason for this is simple: shady sites used to abuse this to kingdom come in the past to trap users, and in turn, modern browsers extensively limit the damage you can possibly do with this. What's your use case? – John Weisz Mar 25 '23 at 14:50