This is more of a JavaScript the A WordPress Question but anyway, You can use the JavaScript onbeforeunload
event something like:
<script type="text/javascript">
old = window.onbeforeunload;
window.onbeforeunload = MyOnExit;
function MyOnExit(){
//do your stuff here
return old();
}
</script>