1

What options do I have preventing the user from just closing the browser or navigating to another site? (of course I can't prevent him pulling the plug on the computer, etc.: I just want to show him a warning)

akosch
  • 4,196
  • 7
  • 58
  • 80
  • Duplicate - the exact same question was asked nine minutes before: http://stackoverflow.com/questions/1299452/how-do-i-stop-a-page-from-unloading-navigating-away-in-js – NickFitz Aug 19 '09 at 13:30

2 Answers2

6

You could use the JS beforeunload event in order to achieve this.

Wesley Murch
  • 98,378
  • 36
  • 187
  • 224
KB22
  • 6,699
  • 8
  • 41
  • 52
1

You should use the onunload event.

<script>
function onExitHandler() {
  // called when user about to leave the page
}
</script>
<body onunload="onExitHandler()">
...
</body>

You can see an example here: http://www.w3schools.com/jsref/jsref_onunload.asp

Itay Maman
  • 29,207
  • 10
  • 83
  • 115
  • 4
    The unload event is too late. You have to use beforeunload if you want to prevent the user leaving (which was the question). – jhurshman Aug 19 '09 at 12:49