Calling JavaScript function in a .js file from Java
-
04-12-2019 - |
Pergunta
What is the best way to call a JavaScript function in a different .js file from a Java file?
Say, I have a String like so in a Java file:
String test = "[name1, name2, name2]";
What I am trying to do is the following:
- Convert the Java String into a JavaScript array
- Pass the JavaScript array to a JavaScript function in a different .js file.
Thanks, Sony
Outras dicas
If you want to integrate Javascript and Java, then you can use Rhino. See the example below for a better comprehension:
test.js
function test(array){
for(var i in array){
out.println(array[i]);
}
}
RhinoTest.java
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
public class RhinoTest {
public static void main(String[] args) {
Context ctx = new ContextFactory().enterContext();
Scriptable scope = ctx.initStandardObjects();
try {
Object out = Context.javaToJS(System.out, scope);
scope.put("out", scope, out);
FileReader fr = new FileReader("test.js");
ctx.evaluateReader(scope, fr, "<cmd>", 1, null);
fr.close();
String[] strArray = {"name1","name2","name3"};
Object jsArray = Context.javaToJS(strArray, scope);
scope.put("jsArray", scope, jsArray);
ctx.evaluateString(scope, "test(jsArray)", "<cmd>", 1, null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Context.exit();
}
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow