14

I need to open a JSF page in a new window by POST on click of a <h:commandButton>. I know I can acheive this using the JavaScript. But I would like to achive this using JSF and not JavaScript.

How can I achieve this? I'm using JSF 2.0.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
vr3w3c9
  • 1,118
  • 8
  • 32
  • 57
  • has to be a window? or can it be a new tab? – damian Jul 23 '12 at 11:49
  • New tab is also fine. When You click on the command Button I want a page to be opened in a new tab. – vr3w3c9 Jul 23 '12 at 11:51
  • in a commandLink, you achieve this adding target="_blank", but I think there's no way to do this in a commandButton without javascript – damian Jul 23 '12 at 11:56
  • Thanks Damian, for the inputs. I have already been able to establish this using commandLink. But I would like to acheive the same using commandButton. Also is there anyway if we can specify the javascript code in the backend to open the page in a new tab?? please assist. Thanks in Advance. – vr3w3c9 Jul 23 '12 at 12:23

2 Answers2

33

The only non-JS way is to set target="_blank" in the parent <h:form>.

<h:form target="_blank">
    ...
    <h:commandButton value="Open in new Window" />
</h:form>

This however affects all non-ajax(!) actions which are performed in the very same form. So if you're smart, make the action which shouldn't open in a new window an ajax action. However, ajax is also JavaScript and you mentioned that you don't want to use JS (I hope you don't get shocked once you discover that PrimeFaces is actually full of JavaScript).

If you absolutely need to restrict it to a single action, then you really can't go around asking little help to JavaScript.

<h:form>
    ...
    <h:commandButton value="Open in new Window" onclick="this.form.target='_blank'" />
</h:form>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
5

When you restrict the target only to a single action, maybe you want to get the form in its initial state. With the onclick action you set the target of the form to a _blank page. After the click, the page is opened in a new tab/page (triggers the action event). At last, the onblur action is triggered and sets the form again to its initial state (the rest of the buttons will open in the _self page) With this code, you can restrict to only a h:commandbutton to open in a new page. The rest of the buttons will be opened in the _self page:

    <h:commandButton
       onclick="this.form.target='_blank'"
       onblur="this.form.target='_self'"
       id="listadoRebuts"
       action="#{giaquaBusquedaCorte.abrirListadoRebuts}"
       value="#{msg.seqVisorbtnRecibos}">
    </h:commandButton>
Mike Lowery
  • 2,630
  • 4
  • 34
  • 44
goojoob
  • 51
  • 1
  • 1
  • From the question: *"I know I can acheive this using the javascript. But I would like to acheive this using JSF code and not Javascript."* – BalusC Mar 27 '13 at 12:27