Alex Rivera | Logout

Calling a JavaScript function from managed bean

Asked 2011-04-15T09:49:01.063
50

Is there a way to call (execute) a JavaScript function from managed bean in JSF?

If that's relevant, I'm also using PrimeFaces.

Edit
Report

2 Answers

38

Depending on which version of Primefaces you're on you can use RequestContext.execute("{js here}");

From the Primefaces 3.4 documentation:

RequestContext provides a way to execute javascript when the ajax request completes, this approach is easier compared to passing callback params and execute conditional javascript. Example below hides the dialog when ajax request completes;

Code

public void save() {
  RequestContext requestContext = RequestContext.getCurrentInstance();  
  requestContext.execute("dialog.hide()");
}
answered 2012-11-20T13:23:19.893
1

In general, Java provides an API to evaluate a string using a scripting engine. This can be accomplished by javax.script.ScriptEngine and javax.script.ScriptEngineManager classes.

I am not entirely sure what your situation is, but if you can pass the javascript as a string to the managed bean, you could probably use Java scripting API to run the javascript on the server side.

For more information, check out this link: http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

answered 2012-03-16T23:52:31.627

Your Answer