geoffs3310
geoffs3310

Reputation: 14008

Prevent window closing with jQuery?

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.

Upvotes: 3

Views: 10629

Answers (4)

Hugo
Hugo

Reputation: 1672

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?

Upvotes: 0

Will Vousden
Will Vousden

Reputation: 33408

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!

Upvotes: 0

user32826
user32826

Reputation:

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.

Upvotes: 2

Pekka
Pekka

Reputation: 449843

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.

Upvotes: 5

Related Questions