In this recipe, we propose to see how to open a pop-up window using JSF and JS. Actually, we will open a pop-up window using JSF and JS using:
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
We can have many approaches to accomplish this task, but we prefer to present two of them. We start with opening a pop-up window using the target
attribute of the h:commandLink
component—"The target
attribute identifies the name of a frame into which the resource retrieved by this hyperlink should be displayed."—JSF HTML Tag Reference definition. The following is the source code:
<h:commandLink target="NewWindow" action="#{bean.actionNewWindow}" actionListener="#{bean.listenerNewWindow}" value="Open Popup Window 1" />
Another approach uses the JSF h:outputLink
component. This time we use the onclick
event and the window.open
call:
<h:outputLink onclick="window.open('newwindow.xhtml', 'MyWindow', 'dependent=yes, menubar=no, toolbar=no'), return false;" value="#"> <h:outputText value="Open Popup Window 2" /> </h:outputLink>
As a third approach we also use the h:outputLink
, but this time the JS code is moved into a function, as shown next:
function openNewWindow(){ //alert('#{facesContext.externalContext.requestContextPath}/ newwindow.xhtml'), window.open('#{facesContext.externalContext.requestContextPath}/ newwindow.xhtml', 'MyWindow', 'dependent=yes, menubar=no, toolbar=no'), return false; } … <h:outputLink onclick="openNewWindow();"> <h:outputText value="Open Popup Window 3" /> </h:outputLink>
The first approach is very intuitive, since the definition of the target
attribute is very clear. The next two approaches use the JS window.open
object. This object provide a set of attributes that allows us to open a popup and to customize different aspects, such as size, scrollbars, menubars, and so on.