2

I need to do this from Java code, I was trying the following, but got stuck:

    UIOutput js = new UIOutput();
    js.setRendererType("javax.faces.resource.Script");
    js.getAttributes().put("library", "js");
    js.setValue("alert(123);");

    FacesContext context = FacesContext.getCurrentInstance();
    context.getViewRoot().addComponentResource(context, js, "body");

I didn't get an error with this in the server log, but also didn't see the alert.

Any idea?

EDIT: I tried the suggested solution, the alleged duplicate, and I didn't get a server error either, but neither did I see any alert..

3
  • Why do you create components using Java code? Commented Apr 1, 2015 at 18:47
  • @Tiny because he tried to create something that would dynamically run a script Commented Apr 1, 2015 at 19:01
  • 1
    possible duplicate of Initiating JavaScript call from server side Commented Apr 1, 2015 at 21:36

3 Answers 3

2

I'm assuming you want to do this from a JSF ManagedBean, not a JSF Component.

I'm not sure there is a 'plain' jsf solution for this (meaning not adding another framework or creating and maintaining some specific java code).

There are at least 2 solutions (the ones I worked with):

I'm sure all other component suites (RichFaces, IceFaces, OpenFaces, ...) have some similar solution.

If you want to stay using plain JSF, I'd go for using OmniFaces. It's a great addition in general and prevents you from maintaining knowledge about implementation specifics.

Edit: I just found a plain jsf solution

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! Actually I'm using RichFaces, I will google for something similar there!
There doesn't seem to be something similar in RichFaces, do you know anything?
I tried that, but I'm getting an JSF AJAX Error: description: "An empty response was received from the server. Check server error logs.", responseCode: 200, responseText: "<?xml version='1.0' encoding='UTF-8'?>↵<partial-response><changes><eval><![CDATA[alert(123);]]></eval>", responseXML: null and I don't see the alert
Then I think your richfaces ajax response handler does not seem to support this and I'm out of suggestions.
Although, you could try to add a dummy update to 'satisfy' the ajax response handler and parse the response yourself and 'eval' the javascript part
|
-1

Please try this:

JavaScriptRunner.runScript(FacesContext.getCurrentInstance(), "alert(hello)");

Comments

-1

I don't know my version. But I tried the follows and it works in my environment

FacesContext.getCurrentInstance().getResponseWriter().write("<script>alter('hello');</script>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.