Wednesday, July 8, 2009

JavaScript and Applet Communication

Sometimes it's necessary to make an applet talk to JavaScript in the html page that contains it and vice versa. LiveConnect is the technology that makes this possible. And the best part is that you don't even have to download anything, because the component that enables JavaScript to talk to applet is supported by Firefox, Internet Explorer and Safari, and the component that enables an applet to talk to JavaScript is plugin.jar, which comes with the JRE.

JavaScript to Java Applet

For JavaScript to call methods in a Java applet, the applet must be named in the applet tag and the mayscript attribute set to true. For example, if I have an applet called JSApplet, then the applet tag may look like this:
<applet code="com.avacoda.swing.JSApplet"
mayscript="true" name="jsApplet" width="200" height="100">
If JSApplet has a method called setMessage(), then the JavaScript can access this method like so:
jsApplet.setMessage("Hello");

Java Applet to JavaScript

To perform the converse operation, the Java applet has to import the JSObject class. The JSObject class is a wrapper around JavaScript objects.

For example, the following code gets the JavaScript window object in the page that the applet referred by this resides in. Then, it gets the document object of the window and finally the form object in the document.
JSObject window = JSObject.getWindow(this);
JSObject document = (JSObject) window.getMember("document");
JSObject form = (JSObject) document.getMember("form");

Download
Source Code

Run JSApplet
This sample code contains a JSApplet that, when initialized, calls the JavaScript setMessage() method, which in turn calls back to the JSApplet's setMessage() method. The JSApplet's setMessage() method repaints the screen with the message that is passed from itself to JavaScript and back to itself again.

Note: This sample code works on Firefox and Internet Explorer, but this "closed-loop" program appears to be incompatible with Safari, though it does not appear to fail. Nonetheless, an applet can still communicate with JavaScript and vice versa in Safari.

References
  1. LiveConnect Overview, Mozilla Developer Center.
  2. Talk to JavaScript with Java, NetSpade Web Developer Heaven, 2005.

No comments:

Post a Comment