WebObjects/Web Applications/Development/Examples/Open Link in New Window

Opening a link in a new window using JavaScript. There's actually a surprisingly easy way to do it. Just use a WOHyperlink, with an onclick binding.

 Hyperlink3: WOHyperlink {
       action = myCustomAction;
       onclick = "return openInNewWindow(this)";
       target = "_new";
 }
 <script language="javascript">
 function openInNewWindow(senderLink) {
       url = senderLink.href;
       newWindow = window.open(url,"NewWindow","width=650,height=600,resizable=yes,"+
               "scrollbars=yes,location=no,toolbar=no");
       newWindow.focus();
       return false;
 }
 </script>

The interesting this is, the hyperlink is sending itself to the openInNewWindow?() function, which then gets the URL from the href property of the link, and opens it in a new window. You can use a regular old action method and bind it to this hyperlink. Also, it will work in browsers that don't have javascript, because the function will not return false, and the link will act like a regular hyperlink whose target is "_new". When the javascript returns false, the link is not followed.

To do something a bit more complex, suppose you are storing image dimensions in the database, and want the newly opened window to be exactly the right size. You will need to programatically create the "onclick" binding string for the WOHyperlink, which will pass the dimensions to the openInNewWindow?() javascript function.

 Hyperlink3: WOHyperlink {
       action = myCustomAction;
       onclick = myOnclickString;
       target = "_new";
 }

and in your component class, add the following method:

 public String myOnclickString() {
       EOEnterpriseObject imageBeingOpened; // assume this exists
       Integer width = imageBeingOpened.width();
       Integer height = imageBeingOpened.height();
       return "return openInNewWindow(this, " + width + ", " + height + ");";
 }

And finally, change your javascript method to accept the width & height parameters:

 <script language="javascript">
 function openInNewWindow(senderLink, width, height) {
       url = senderLink.href;
       newWindow = window.open(url,"NewWindow","width="+width+",height="+height+",resizable=yes,"+
               "scrollbars=yes,location=no,toolbar=no");
       newWindow.focus();
       return false;
 }
 </script>
Last modified on 11 May 2009, at 20:51