JavaScript trap and cancel window close event

Getting straight to the point, the following JavaScript code will present users with a dialog warning whenever they try to navigate away from a page (working example here):

<html>
<head>
<script type="text/javascript">
window.onbeforeunload = function (evt) {
return "DON'T DO IT!";
}
</script>
</head>
<body>
<h3>Try to close me or navigate away...</h3>
</body>
</html>

Yes, it's that simple. Whenever the user tries to navigate away from the page in any way (refresh/back/forward) or to close the page by closing the browser tab or browser window itself, they are prompted with a dialog box asking them to confirm the action. If the user selects cancel, the page navigation or browser close event is discarded. I'll repeat that again - the browser will not close if the user presses cancel! I've tested this and it works in Firefox 3+, Google Chrome and IE8+ (not sure about IE6 or IE7).

The reason I post this is because I've had a recent use-case for this behaviour and a lot of online forums I came across said it can't be done. Many may also argue that such behaviour should never be implemented, i.e. if a user clicks the close button, then let them close the page! But what if the user just spend 10 minutes filling out a long form and accidentally clicked the small close button at the top of the tab, or what if the user is interacting with a complex web-application in which they must complete a sequence of steps spanning multiple pages... a warning to prevent against accidental or incomplete session termination can be very useful.

Note though that the exact wording of the dialog varies from browser to browser. All will include the "DON'T DO IT" message, but will also include an 'Are you sure?' type question at the bottom, and possibly a 'You tried to navigate away from this page' type statement at the top.

Comments

  1. Just what I needed. Thanks...

    ReplyDelete
  2. thx this help me alot :D

    ReplyDelete
  3. Hi, is there any way to cancel the close event without displaying the Confirm Dialog box. So that though the user clicks on the close button,window shouldn't be closed.

    Plz reply me asap majetyravi@gmail.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word