1

Is it possible to cancel the browser close window event? Or at least add a message prompting the user whether they are sure they want to leave the page? I tried doing this with the beforeunload event, but it still closes the browser. I am looking for something similar to Microsoft's exchange website.

Thanks!

enter image description here

Misha Ts
  • 431
  • 1
  • 4
  • 16
ntsue
  • 2,325
  • 8
  • 34
  • 53
  • 2
    I'd strong advise against this. One of the most annoying features you can implement from a user experience perspective. But you can try this:http://api.jquery.com/unload/ – Abe Petrillo Mar 13 '12 at 16:40
  • Sorry, C# was the server side code I was using. I guess it doesn't matter, I'll remove the tag. – ntsue Mar 13 '12 at 16:56
  • See this StackOverflow question: http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch – Michael Rice Mar 13 '12 at 17:00

5 Answers5

3

Here is an Html Code:

<html>
<head>
<script language="javascript" type="text/javascript">
window.onbeforeunload = askConfirm;
function askConfirm(){
        return "You have unsaved changes.";
        }
</script>
</head>
<body>
</body>
</html>

Paste this code into the text area on this page: http://www.htmlpreview.richiebrownlee.com press the button, then exit out of the page that comes up..

  • I don't think this is widely supported. It'll work in IE but some Mozilla browsers, etc. don't support it – Liam Mar 13 '12 at 16:46
  • i tried it on chrome and it works, but thanks for the notification! –  Mar 13 '12 at 16:49
2

a ha!

It appears there's a supported JQuery solution

   $(window).unload(function() 
{
  //...
});

http://www.webhostingtalk.com/showthread.php?t=927093

this should be cross browser supported...hopefully....

Liam
  • 27,717
  • 28
  • 128
  • 190
1

window.onbeforeunload

Will work on Safari, IE, Firefox, Chrome, but not Opera.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
0

onbeforeunload should work fine. Bind this on body/window attribute of the html. For more details check this detailed blog post, blog

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
0

use onbeforeunload event http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx

<HTML>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com">Click here to navigate to 
      www.microsoft.com</a>
</body>
</html>
Misha Ts
  • 431
  • 1
  • 4
  • 16