views:

894

answers:

2

Say I have some javascript that if run in a browser would be typed like this...

  <script type="text/javascript"
      src="http://someplace.net/stuff.ashx"&gt;&lt;/script&gt;

  <script type="text/javascript">
     var stuff = null;
     stuff = new TheStuff('myStuff');
  </script>

... and I want to use the javax.script package in java 1.6 to run this code within a jvm (not within an applet) and get the stuff. How do I let the engine know the source of the classes to be constructed is found within the remote .ashx file?

For instance, I know to write the java code as...

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");

    engine.eval( "stuff = new TheStuff('myStuff');" );
    Object    obj = engine.get("stuff");

...but the "JavaScript" engine doesn't know anything by default about the TheStuff class because that information is in the remote .ashx file. Can I make it look to the above src string for this?

+2  A: 

It seems like you're asking:

How can I get ScriptEngine to evaluate the contents of a URL instead of just a string?

Is that accurate?

ScriptEngine doesn't provide a facility for downloading and evaluating the contents of a URL, but it's fairly easy to do. ScriptEngine allows you to pass in a Reader object that it will use to read the script.

Try something like this:

URL url = new URL( "http://someplace.net/stuff.ashx" );
InputStreamReader reader = new InputStreamReader( url.openStream() );
engine.eval( reader );
Stephen Deken
No, as far as I know, the ashx file contains the javascript objects that the browser needs to do what it needs to do. But I want to run this in a jvm and not in my browser. So the url is not the script but the source of the compiled objects to use in a script.
A: 

Are you trying to access the javascript object in the browser page from a java 1.6 applet? If so, you're going about it in the wrong way. That's not what the scripting engine's for. It's for running javascript within a jvm, not for an applet to accesses javascript from with in a browser.

Here's a blog entry that might get you somewhere, but it doesn't look like there's much support.

sblundy
I am trying to run javascript within a jvm, but the javascript classes I want to use are not standard classes but rather are in this src file.