Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript function from java

I want to know if it's possible to execute a javascript function from java. Basically I have a javascript function to which I want to pass a string and then get the output from that function.

If it's possible, how do I accomplish it?

EDIT -

I couldn't find a solution to this, what I did was re-write all the javascript code in Java. But I am guessing, Rhino ported on Android should do the trick. If someone has tried it out, please post a solution.

like image 676
Hades Avatar asked Nov 28 '11 09:11

Hades


People also ask

Can you call a JavaScript function from Java?

The following code shows how to call Javascript functions from Java. First, it defines four functions in the Javascript file and saves it to the c:/Java_Dev/calculator. js. var calculator = new Object(); calculator.

How do you execute a JavaScript function?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.

How do you write a JavaScript function in Java class?

getEngineByName("JavaScript"); // JavaScript code in a String String script1 = "function hello(name) {print ('Hello, ' + name);}"; String script2 = "function getValue(a,b) { if (a===\"Number\") return 1; else return b;}"; // evaluate script engine.


2 Answers

You probably want to take a look at the ScriptEngine. There are plenty of samples out there on how to use it. Works on anything but Mac where they for some reason selected to include AppleScript instead of JavaScript by default.

Edit: Take a look at this page, there seems to be a Rhino port for Android out there.

like image 70
Fredrik Avatar answered Oct 06 '22 01:10

Fredrik


Javascript is not natively supported in java. If you need it, you may implement the Rhino javascript engine to do this.

"Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users."

like image 29
Flavien Volken Avatar answered Oct 06 '22 01:10

Flavien Volken