onbeforeunload or onunload
As you can see this approach is pretty strait and suppose to work. But it doesn't work always, in fact it doesn't work at all! well these two event fires each and every time on these operations.
- post back
- navigate to another page
- close the browser
- close the current tab
There could be more cases that I haven't encountered yet or failed to mentioned, but these are the most renowned cases. As you can see that the first three cases happens very frequently, so this technique does not work. Yet there are other solutions for overcoming the problem. Here is a forum discussion on that http://codingforums.com/archive/index.php?t-37279.html. You can find more discussion if you Google it.
Extending the onbeforeunload technique
If we handled the case of post back, navigate and refresh, "close event" detect will be fulfilled. So we are going to use some old fashion technique to handle that. If you want to perform any operation in html using mouse, you have to click on some kind of html element to do that. And that's why we will trap the mouse down event. We will mark any kind of mouse down on link, button, and any element so that when post back or navigate we can detect that, its happening because of user interaction on page. Next we will trap any special key event to make the page refresh or reload, for instance pressing Ctrl+f5,f5 and Ctrl+R can make the page refresh so we will also mark such kind of keyboard operation. So we will mark any kind of keyboard event and any kind of mouse event, other than those already mentioned case we are not marking the Alt+f4 or the browser or tab close. So if our window close event fires it happen definitely because of closing the browser or closing the tab. Bellow a simple code snippet is given to demonstrate the idea.
As we have already discusses that there is no 100% full proofed way to detect the browser close event in lot of case the above technique can failed, for example if the user kill the browser's process from task manager there could be many more cases. Yet in lot of case this technique can be handy. Best of luck and happy programming.