Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling javaScript from java method

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');");
like image 486
Abhijit Desai Avatar asked Dec 20 '15 16:12

Abhijit Desai


People also ask

Can we call Java method from JavaScript?

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 I connect JavaScript to Java?

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.

Can JavaScript use Java classes?

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.


2 Answers

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.

like image 178
christopher clark Avatar answered Nov 14 '22 23:11

christopher clark


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

like image 36
M Sach Avatar answered Nov 14 '22 22:11

M Sach