9

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,

2 Answers 2

8

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.

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

Comments

0

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.

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.