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,326
  • 7
  • 59
  • 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
  • 101,186
  • 37
  • 194
  • 228
KB22
  • 6,899
  • 9
  • 43
  • 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
  • 30,277
  • 10
  • 88
  • 118
  • 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