Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 504
ashkrosh Avatar asked Apr 24 '10 12:04

ashkrosh


People also ask

Can we call JavaScript function from Java?

JavaScript cannot call java method directly since it is on the server. You need a Java framework like JSP to call when a request is received from JavaScript.

How do you call a function in Groovy script?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.


1 Answers

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.

like image 97
coobird Avatar answered Nov 05 '22 08:11

coobird