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');");
1
  • Try eval("alert(\"HI\")"); Commented Dec 20, 2015 at 17:49

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You need to escape the quotes around Hi
can you please give link where i can see some examples/tutorials of using js in java
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

2 Comments

It is possible through scripting API, which OP is using: docs.oracle.com/javase/8/docs/technotes/guides/scripting/…
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
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

Comments

-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.

2 Comments

I mean it's no different than calling powershell functions with .Net. Or Sql statements...
Serverside scripting is an elegant thing and can even be sophisticated architecture

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.