OnUnload Event
OnUnload Event is responsible for executing an instruction when page is closed. But beware when it comes to browsers like internet Explorer and AJAX at same time. If the statement involves AJAX, it is even more doomed, and the user will probably be very sad.
This event is defined in HTML 4.0.
Example
<script type="text/javascript">
window.onunload = CallExit;
function CallExit() {
return "going to close";
}
</script>
Above example will run the script before the window close event is fires.
OnBeforeUnload Event
OnBeforeUnload Event works a little different OnUnload. It is more efficient because it does not run in competition (with / at the same time) with the closing of the window, which can cause something to be charged in half (so unfinished).
Example
<script type="text/javascript">
window.onbeforeunload = CallBeforeExit;
function CallBeforeExit() {
return "Are you sure to close aspxtutorial.com";
}
</script>