File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes trace the browser window closing in a servlet/jsp Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "trace the browser window closing in a servlet/jsp" Watch "trace the browser window closing in a servlet/jsp" New topic

trace the browser window closing in a servlet/jsp

Ven Ram

Joined: Sep 15, 2003
Posts: 11
Hi All,
Is there any way to trace the browser window closing in a servlet/jsp? If some one clicks on the x of the browser, How can we trace ?

Please help me.
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

JSP/Servlet == server side. Browser events == client side. So no. The only thing a Servlet (and hence a JSP) in its typical context is going to know about is an HTTP request. Since closing the browser doesn't make any request to the server, not message is passed to the Servlet. You need JavaScript for browser events.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
and even then there's no guarantee.

Not all ways in which a browser window can be closed will result in a Javascript event being fired.

If there were you could in a Javascript event handler do a request to the server which would launch some cleanup code or whatever, but this isn't reliable (as we found out, one of our marketing people had thought up a requirement to do exactly that, we had to tell him it wasn't possible and to train the users to use the logout button instead).

Eric Pascarello

Joined: Nov 08, 2001
Posts: 15385
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.

Also the onunload event will not fire if user gets disconnected from internet, user's browser freezes, or my favorite reason "If JavaScript is disabled by the user"

That is why I really on my session timing out on the server to clean up the mess.

Eric Pascarello
I agree. Here's the link:
subject: trace the browser window closing in a servlet/jsp
jQuery in Action, 3rd edition