开发者

Call javascript function from Java (Groovy) class

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 c开发者_JAVA百科an 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,


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜