How to open a new window from an Action

Another frequent question on the mailing lists is how to open a new browser window from an Action. This one won't take too long:

YOU CAN'T!

:)

Strictly-speaking, this is true... code running on the server has no way to tell the browser to open the response in a new window. That being said, there ARE a couple of ways to get the desired effect.

   s = "";
   s += "<html><head><title>Results</title></head><body>";
   s += "These are my results";
   s += "</body></html>";
   w = window.open("", "Results", "resizable,height=200,width=200");
   w.document.open();
   w.document.write(s);
   w.document.close();

Imagine generating this in an Action, where the string "These are my results" is replaced by a full HTML page (properly escaped of course). Yes, you could generated the response with a JSP, which is what I would recommend. That might be confusing, so let me explain... a JSP does NOT have to render a complete HTML document. It can instead render just a snippet of HTML, or just some Javascript, or just some comma-separated data, there is no limitation. If you are doing AJAX, whatever is most appropriate can be done via JSPs (like XML too!). This saved you from writing a lot of println's in your Actions to generate a response.

Now, if you make an AJAX call to this Action, and return this content and execute it, you will get your response opened in a new window. Neat, huh?!? If you decide to go this route, I suggest checking out the AjaxParts Taglib in the Java Web Parts project (http://javawebparts.sourceforge.net). It will allow you to put a single custom tag on your page and save you from having to write the AJAX code or the code to execute the returned results (although you will still have to write the code in the Action).

Takeaway point

The important point to take away from all this is that aside from the target attribute on the form tag, Javascript is involved. There is currently no good way to avoid that (and someone can correct me if I missed something). If you are working in an environment where scripting is a problem, you may want to revisit your design and see if you really need a new window at all.

OpenWindowFromAction (last edited 2009-09-20 23:11:42 by localhost)