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.
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.
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.
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.
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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With