Friday, April 24, 2009

Java Applets and Javascript

Everyone knows that you can use javascript to manipulate java applets.

Take for example, I have an applet with a public method called doSomething().  All one has to do to execute this method from javascript is to get a handle on the applet and call the method:

<applet id=”test” …>

<script type=”text/javascript”>
document.getElementById(‘test’).doSomething();
</script>

I found out today that you can use java applets to fire javascript functions and manipulate the DOM in the browser with a little extra tweaking.  The Java plugin comes with some classes in the ‘netscape’ package that allows for this interaction…(yes it works in IE also)…All you have to do is get a handle on the window that holds the current applet.  Consider the following example:

public class SomeApplet extends JApplet
{
  public void init()
  {
     final JSObject jso = JSObject.getWindow(this);
     final Object out = jso.call(“someFunction”,
               new Object[]{ “testParam” });
     System.out.println(“Output from function: “ + out);
  }
}

<script type=”text/javascript”>
   function someFunction(msg) {
       alert(msg);
       return “the output”;
   }
</script>

This simple example calls the javascript function from within the applet and read back the output of the function as an Object.  The one thing that you must do is enable scripting of the applet:

<applet … mayscript />

If you don’t add the mayscript parameter to your applet, you will get a JSException that tells you nothing.

No comments: