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

About these ads
  1. June 21, 2010 at 8:45 am | #1

    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 | #2

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

    • June 22, 2010 at 1:17 am | #3

      Hi Puran,

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

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

    Thanks! It was helpful!

    • June 22, 2010 at 10:39 am | #5

      Hi Tilak,

      Thanks for your encouragable comments.

  4. June 30, 2010 at 2:53 am | #6

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

      Hi Javascript Examples,

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

  5. July 7, 2010 at 5:51 am | #8

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

  6. October 16, 2011 at 11:37 pm | #9

    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 | #10

    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 | #11

    very useful

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

    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 | #13

    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 | #14

    hi,
    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 | #15

      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 | #16

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

  12. Maxim
    February 19, 2013 at 10:19 pm | #17

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

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

    File Not Found Exception occured

    • Priya
      October 25, 2013 at 7:33 am | #19

      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 | #20

    thanx saved ma life

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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: