File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Struts and the fly likes catching page change or browser close Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "catching page change or browser close" Watch "catching page change or browser close" New topic

catching page change or browser close

J P Nelson

Joined: Dec 16, 2004
Posts: 12
Is there a struts way to trap when the user navigates out of an application or closes the browser? We would like to catch this and give them a chance to save their work before doing leaving so un-gracefully.
Henrique Sousa
Ranch Hand

Joined: Apr 29, 2004
Posts: 92
Short question, long answer

Problem #1: the request-response model. Once you send the response, there is absolutely no news from the browser until the next request. So what you need is to capture some client-side event (using JS perhaps) and send a request representing this event back to the server.
Problem #2: you are not able (at least you shouldn't be able) to control the client environment like asking confirmation to close the browser window. Therefore even if you can redirect to some confirmation page, the browser would be closed. Yes, you could use client-side script to open a new window, but I think that is quite annoying. In case the user navigates to another domain, you could send him back to your system using that client-side event, but that's just as annoying IMO.
So there is no struts way to trap when the user navigates out of an application or closes the browser as far as I know.
One solution is to use the onunload event to check when the page changes or the window is closed. But you cannot see what is the next location, so you should set some flag before assuming anything. Some example code:

What do we have here? If the user clicks the submit button, navigation proceeds as usual (you can use onclick event of html anchors too). If he types an URL in the browser, the current form data is sent to an action for confirmation or logout procedures in a new window. It is very respectful for that window to close itself once its work is done. We have adopted a similar solution, so it should work at least to some extent.

Henrique Sousa<br />SCJP 1.4<br /> <br />All men die, not all men really live - Braveheart, 1995
I agree. Here's the link:
subject: catching page change or browser close
jQuery in Action, 3rd edition