There is no way to detect when the browser window is closed...onunload is the closest you are going to get to it.
Just a few points to ponder as you develop this application: You need to consider that the onunload gets called when the page is closed, user navigates away by link or typing in the url, and refreshing the page. So if you need to distinguish between these, then you will have some difficulty.
That is why I really on my session timing out on the server to clean up the mess.
subject: trace the browser window closing in a servlet/jsp