Home > Uncategorized > Execute Javascript from Java

Execute Javascript from Java

After a small gap,I am back to here for share something to you all.A week before i have stuck with execute javascript from java.I google it for this.Finally i found my way to achieve this.

Java provides the way to execute JavaScript also.The solution is come along with ScriptEngineManager.This article deals the same.

The ScriptEngineManager comes along with the package javax.script.

This is a relatively small, simple API. A ScriptEngineManager object can discover script engines through the jar file service discovery mechanism. It can also instantiate ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use the scripting API is as follows:

  • Create a ScriptEngineManager object.
  • Get a ScriptEngine object from the manager.
  • Evaluate script using the ScriptEngine’s eval methods.

Now we look at the sample code.

import javax.script.*;
public class ExecuteScript {
 public static void main(String[] args) throws Exception {
 // create a script engine manager
 ScriptEngineManager factory = new ScriptEngineManager();
 // create a JavaScript engine
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 // evaluate JavaScript code from String
 engine.eval("print('Welocme to java world')");

Executing a Script from .js File:

In this example, we can execute JavaScript which is from .js file.This can be achieved by the eval method of ScriptEngine Class.
The eval method have the FileReader object as argument.

we can create the ScriptEngineManager and get the ScriptEngine from the above code(line 4-7).

Then we add the eval method which is used to execute script from .js file.

// evaluate JavaScript code from given file
 engine.eval(new java.io.FileReader("welcome.js"));

Let us assume that we have the file named “welcome.js” with the following text:

println("Welcome to java world");

If we will run the code,this yields the output as

Welcome to java world.

I hopes this helps.Then Go ahead to execute your JavaScript by using your java code.Before that,if you feel it useful,leave your foot prints here[Comments].

  1. June 21, 2010 at 8:45 am

    To learn php,html,javascript,ajax,mysql,jquery with advanced concepts, you can visit http://advancedphptutorial.blogspot.com

  2. June 21, 2010 at 9:35 pm

    cool..never explored this i will try for sure.

    • June 22, 2010 at 1:17 am

      Hi Puran,

      Thanks for your valuable comments.Keep try and explore the result.

  3. Tilak
    June 22, 2010 at 6:13 am

    Thanks! It was helpful!

    • June 22, 2010 at 10:39 am

      Hi Tilak,

      Thanks for your encouragable comments.

  4. June 30, 2010 at 2:53 am

    that’s all cool tips, thank you very much for sharing.

    Can you give me a favor to share this post on my JavaScript library?

    Awaiting your response. Thank

    • July 10, 2010 at 2:48 pm

      Hi Javascript Examples,

      I am so glad to hear from you.Go ahead.

  5. July 7, 2010 at 5:51 am

    Najlepsza strona – [url=http://nostradamo.pl/]audiobooki[/url]

  6. October 16, 2011 at 11:37 pm

    Greetings! it worked for me. but I’d to show for example: alert(“Please insert something in the textField”); how can I call that alert, I write that in the script.js but it doesnt work please help!

  7. Nadeem
    March 8, 2012 at 1:58 pm

    I tried several times to execute this code but could not achieve it.

    Can you please guide where exactly the set of code will be present?

    as of now i got that ” println(“Welcome to java world”);” will be in a welcome.js file wot about the rest?

    please provide a wholesome application, m a beginner.

  8. bluesky
    May 11, 2012 at 10:31 pm

    very useful

  9. vesadi
    June 18, 2012 at 7:52 pm

    very useful!!. Can you please explain how to capture the return value from a js in java?

  10. Toneloc
    August 25, 2012 at 4:04 pm

    Thank you for posting this article, as it has been very useful. However, I’m still at one brick wall when it comes to evaling JS from Java: I am writing a web application whose elements are to be dynamically controlled by a Java Applet (swing). Using this suggestion seems to be putting me outside the DOM scope; for example, the alert() method is not defined and unavailable.

    Could this be that the DOM has some instance of ScriptEngine that I’m avoiding by getting an engine from a new ScriptEngineManager? If so, are there any recommendations on how I can reach the DOM scope?

  11. Ravi
    February 8, 2013 at 3:34 pm

    i use this and i have file name as welcome.js in my package..
    engine.eval(new java.io.FileReader(“welcome.js”));
    i got filenotfound exception… can u tell how to include javascript file in java console application…. i’m waiting for ur reply..

    • February 22, 2013 at 5:56 am

      Hi Ravi,

      Checkout the file name and path of the file.I think you wrong in anyone of those information.Otherwise display your project structure here.Then only i ll help you.

    • Karan
      April 2, 2013 at 6:39 am

      If You solve This problem pls help i also got file not found Exception

  12. Maxim
    February 19, 2013 at 10:19 pm

    but how about more practical example? to get a return value or to pass arguments…

  13. Karan
    April 2, 2013 at 6:38 am

    File Not Found Exception occured

    • Priya
      October 25, 2013 at 7:33 am

      Go to the properties of welcome.js and choose the Location: , replace ‘\’ with ‘\\’ and run the code. The statement gets printed.

  14. sabelo
    July 19, 2013 at 11:54 am

    thanx saved ma life

  15. March 24, 2015 at 7:11 am

    in this example, is it possible to run ajax function? that is the js file contains ajax, will the above code run the ajax function in java?

  1. June 20, 2010 at 1:03 pm
  2. June 21, 2010 at 4:28 am
  3. November 18, 2012 at 2:37 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: