简体   繁体   中英

How would I call a JavaScript function from a JSF Bean?

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..

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

请尝试以下方法:

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

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>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM