Reputation: 143
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');");
Upvotes: 8
Views: 9279
Reputation: 1354
It appears that "alert()" is part of the window object provided by web browsers. it doesn't exist here
I have modified java code:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval("print('HI');");
This is useful: Java Scripting Programmer's Guide
Information about javscript window object: The Window Object
Upvotes: 1
Reputation: 34424
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
Upvotes: 1
Reputation: 306
You are doing it the wrong way, you cannot call JavaScript function from java code because one is executed at client side and other at server side...even if you achieve that using some API it's wrong way of architecturing of code.
Upvotes: -2
Reputation: 2113
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.
Upvotes: 2