I want to execute JavaScript function from Java. I used the following piece of code
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
but this throws an exception for the alert()
method ?
engine.eval("alert('HI');");
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.
We'll connect JavaScript to Java by creating a new instance of a Java class using the JavaScript new keyword. Example 1 shows a function named browse() that opens a native "file dialog" using the built-in java. awt. Frame and java.
Calling Java from JavaScript. The Mozilla Rhino JavaScript interpreter bundled with Arbortext Editor provides a mechanism called LiveConnect that lets you use Java classes and methods from JavaScript. The Arbortext Object Model (AOM) classes are written in Java and made available in JavaScript by LiveConnect.
So. I'm pretty sure your code here is incorrect.
engine.eval("alert(HI);");
Try.
engine.eval("alert('Hi');");
unless you have a variable HI declared.
you can not call javascript from java in any way. javascript is client side language and executed on browser where as java is executed on server
Update :- Thanks guys i learnt something new here.
when i execute the code in op i get below error
Error executing script: ReferenceError: "alert" is not defined in <eval> at line number 1
Reason is alert is not part of JavaScript, it's part of the window object provided by web browsers.so, Nashhorn javascript engine does not know about it.
Please see ReferenceError: "alert" is not defined
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