views:

175

answers:

2

Hi, I have a javascript function (very big one!) that I need its functionality in a Java (Groovy) class. It is a simple calendar converter. I can rewrite it in groovy but just want to know if it is possible to call javascript function from a java (groovy) method? I guess functional testing libraries like selenium and Canoo should have something like this, am I right? PS: I don't want to wake up a real-world browser in order to use its JS runtime env.

Thanks,

A: 

You can use Rhino, an implementation of JavaScript language in Java. Here is example of calling JavaScript function from java, but you can do it from groovy also.

Pantokrator
+2  A: 

As mentioned in the other answers, it is possible to use the Scripting API provided as part of the javax.script package, available from Java 6.

The following is a Groovy example which executes a little bit of Javascript:

import javax.script.*

manager = new ScriptEngineManager()
engine = manager.getEngineByName("JavaScript")

javascriptString = """
obj = {"value" : 42}
print(obj["value"])
"""

engine.eval(javascriptString)  // prints 42

It is not necessary to call a browser to execute Javascript when using the Scripting API, but one should keep in mind that browser-specific features (probably the DOM-related functionalities) will not be available.

coobird