Call javaScript from java method

I want to execute a JavaScript function with Java. I used the following code snippet

ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); 

but does this throw an exception for the alert() method?

 engine.eval("alert('HI');"); 
+7
java javascript
source share
4 answers

So. I am sure your code here is incorrect.

 engine.eval("alert(HI);"); 

Try it.

 engine.eval("alert('Hi');"); 

if you do not have a declared HI variable.

+2
source share

It appears that alert () is part of the window object provided by web browsers. does not exist here

I changed the Java code:

 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("print('HI');"); 

This is useful: Java Script Programmer's Guide
Javscript Window Object Information: Window Object

+1
source share

you cannot call javascript from java. javascript is a client language and runs in a browser where java runs on the server

Update: Thank you guys, I learned something new here.

when i execute the code in op i appears below error

 Error executing script: ReferenceError: "alert" is not defined in <eval> at line number 1 

The reason is the warning is not part of JavaScript, it is part of the window object provided by web browsers. In addition, the Javascript Nashhorn mechanism is not aware of this.

See ReferenceError: "alert" not defined

0
source share

You are doing it wrong, you cannot call a JavaScript function from java code, because one is executed on the client side and the other on the server side ... even if you achieve this using some kind of API, this is the wrong way of code architecture.

-one
source share

All Articles