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');");
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
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
您做错了方法,您无法从Java代码调用JavaScript函数,因为一个在客户端执行,而另一个在服务器端执行...即使您使用某种API来实现,这也是错误的代码结构方式。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.