8

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');");
Abhijit Desai
  • 133
  • 2
  • 6

4 Answers4

2

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.

christopher clark
  • 2,026
  • 5
  • 28
  • 47
1

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

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314
  • It is possible through scripting API, which OP is using: https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html – user3707125 Dec 20 '15 at 17:00
  • with help of scripting api we can able to call basic javascript but we cant use any predefined method it will throws an exception so if you know any other solution please provide user3707125 – Abhijit Desai Dec 21 '15 at 18:02
1

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

Community
  • 1
  • 1
Tornike Shavishvili
  • 1,244
  • 4
  • 16
  • 35
-2

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.

Akhil Menon
  • 306
  • 1
  • 9