1

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"></script>

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

Commercial Suicide
  • 13,616
  • 13
  • 48
  • 72
user17978
  • 11
  • 1
  • 4

2 Answers2

2

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
  • 3,535
  • 24
  • 31
  • 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. – user17978 Sep 19 '08 at 15:47
0

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
  • 58,164
  • 22
  • 117
  • 120
  • 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. – user17978 Sep 19 '08 at 15:49