8 Replies Latest reply: Jun 25, 2012 5:02 PM by Simo RSS

    JavaScript from Bean

    Simo
      Hi All,

      I'm using Jdev 11 R2.

      Simply having a bit of a play to increase my knowledge in this area.... aiming to execute a very simple js function through a backing bean - but the message does not show. I have debug messages showing that all lines of code are executed.

      FacesContext fctx = FacesContext.getCurrentInstance();
      StringBuilder script = new StringBuilder();
      script = script.append("alert('Hello World !');");
      Service.getRenderKitService(fctx,ExtendedRenderKitService.class)
      .addScript(fctx,script.toString());

      Is their any reason why the alert message is not shown here?

      There must be some other dependency that I am missing right?

      Simo
        • 1. Re: JavaScript from Bean
          Navaneetha Krishnan Nataraj
          How are you invoking this method from the JSPX Page?

          Thanks,
          Navaneeth
          • 2. Re: JavaScript from Bean
            Navaneetha Krishnan Nataraj
            Check this sample based on your use-case:

            Sample.jspx:
            <?xml version='1.0' encoding='UTF-8'?>
            <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core"
                      xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
                <jsp:directive.page contentType="text/html;charset=UTF-8"/>
                <f:view>
                    <af:document title="Sample.jspx" id="d1">
                        <af:form id="f1">
                            <af:commandButton text="Invoke Button" id="cb1" partialSubmit="true"
                                              actionListener="#{SampleBean.invokeJavascript}"/>
                        </af:form>
                    </af:document>
                </f:view>
            </jsp:root>
            SampleBean.java:
            package com.samples.view;
            
            import javax.faces.context.FacesContext;
            import javax.faces.event.ActionEvent;
            
            import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
            import org.apache.myfaces.trinidad.util.Service;
            
            public class SampleBean {
                public SampleBean() {
                }
            
                public void invokeJavascript(ActionEvent actionEvent) {
                    FacesContext fctx = FacesContext.getCurrentInstance();
                    StringBuilder script = new StringBuilder();
                    script = script.append("alert('Hello World !');");
                    Service.getRenderKitService(fctx, ExtendedRenderKitService.class).addScript(fctx, script.toString());
            
                }
            }
            Thanks,
            Navaneeth
            • 3. Re: JavaScript from Bean
              Simo
              Hi Navaneetha,

              Thanks very much from your response. I am doing exactly that, although I am calling this from a .jsf page.

              Would this be causing the issue?

              Simo
              • 4. Re: JavaScript from Bean
                Frank Nimphius-Oracle
                Hi,

                this should also work from a page fragment.

                Frank
                • 5. Re: JavaScript from Bean
                  Simo
                  Hi again,

                  And thanks Frank also for responding. I know that this one should be a walk in the park, but I've copied the code exactly and still no alert:

                  FacesContext fctx = FacesContext.getCurrentInstance();
                  System.out.println("Context" + fctx);
                  StringBuilder script = new StringBuilder();
                  script = script.append("alert('Hello World !');");
                  Service.getRenderKitService(fctx, ExtendedRenderKitService.class).addScript(fctx, script.toString());

                  System.out.println("JavaScript Aparently Called!" + script);


                  Is there something else that I can check for. It seems that the code executes successfully, but doesn't raise the client js method.

                  Simo
                  • 6. Re: JavaScript from Bean
                    Simo
                    Hi guys,

                    I'm still chipping away at this, and have found a note on Oracle's / Sun's website that provides an example similar to below:


                    ScriptEngineManager mgr = new ScriptEngineManager();
                    ScriptEngine jsEngine = mgr.getEngineByName("js");
                    try {
                    jsEngine.eval("print('Hello, world! This one works.')");
                    } catch (ScriptException ex) {
                    ex.printStackTrace();
                    }

                    Can anyone please shed some light, on the two methods? I can actually get the above to print the line to the console, but when I change the function call to 'alert' this throws an error - guessing that this is NOT the recommended way of executing script from java, however the only one that I can slightly get to work.

                    What am I missing?

                    I am effectively trying to get an action listener to complete before the javascript is executed, and hence trying to call it from my bean.

                    Simo
                    • 7. Re: JavaScript from Bean
                      Sudipto Desmukh
                      try using a clientListener and call a JS method where you enqueue an event to call a server Listener of you need to do anything additional at t java layer in your bean.
                      https://blogs.oracle.com/jdevotnharvest/entry/how-to_call_server_side_java_from_javascript
                      • 8. Re: JavaScript from Bean
                        Simo
                        Hi thanks for your response. I've seen that approach, however that is the reverse of what I am actually trying to do.

                        I need to persist with calling the JS functions from a managed bean. This is the only way I can ensure that the server side logic completes before the JS call.

                        I've copied the code from a number of examples, including that initially suggested, and I still can't seem to get this to work.

                        Are there any other dependencies to this approach? Can anyone offer anything else that I can investigate, as all resources on the net also seem to be a direct copy of a video / white paper that Frank did.

                        Simo