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:
If JSApplet has a method called setMessage(), then the JavaScript can access this method like so:<applet code="com.avacoda.swing.JSApplet"
mayscript="true" name="jsApplet" width="200" height="100">
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 CodeThis 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.
Run JSApplet
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
- LiveConnect Overview, Mozilla Developer Center.
- Talk to JavaScript with Java, NetSpade Web Developer Heaven, 2005.
No comments:
Post a Comment