3

Is it possible to prevent a browser window closing using jQuery? I've tried this:

$(document.ready(function() {
   $(window).unload(function(e) {
      e.preventDefault();
      alert("Not closing");
   });
});

The alert works but the window closes anyway.

KatieK
  • 13,586
  • 17
  • 76
  • 90
geoffs3310
  • 13,640
  • 23
  • 64
  • 85

4 Answers4

5

Fortunately, this is not possible!

You can show a confirmation dialog using onbeforeunload (see e.g. here for how to do it), giving the user the choice to not leave the page after all. But you can't prevent the closing against the user's will.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
2

This would be a huge security issue and while I haven't ever needed to investigate it personally, I doubt any browser would allow you to prevent the window from closing.

0

as other answers say it's not possible to prevent it but you can give the user the opportunity to choose by himself. Maybe you're looking for this...

How can I override the OnBeforeUnload dialog and replace it with my own?

Community
  • 1
  • 1
Hugo
  • 1,662
  • 18
  • 35
0

Doing this would be a fundamental breach of the user's autonomy.! How would you like it if a website were to forbid you from closing your browser?

Your best bet is just to display a confirmation dialogue, as Pekka suggests; you can ask them if they're sure, but ultimately its their decision if they want to close it!

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
  • There are legitimate reasons that you would want to prevent a window from closing. For instance, StackOverflow warns you before closing a window while typing a question or answer. – Vivian River Jul 20 '11 at 22:18