Thursday, March 2, 2006

Calling Javascript functions from a Java Applet

Many years ago, my colleagues encountered a problem that at that time there was no generic solution. The problem was to somehow let the Javascript on a web page to verify that an Applet is loaded correctly without using polling mehtods. Out of curiosity, I tried to find out if browsers today provide a general solution and will work with (at least) both IE and Netscape/Mozilla/Firefox.

It seems that there is a valid solution since IE 4 (and yes, I haven't looked at this problem for a very long time :P). There is a way for an Applet to invoke a Javascript function and will work with both IE and Netscape/Mozilla/Firefox.

First, the applet needs to import the
class "netscape.javascript.JSObject". Although the name says "netscape",
but IE's VM has no problem running the Applet.

(BTW, to compile the Applet, you will need to include plugin.jar in your classpath (e.g. C:Program
FilesJavajre1.5.0libplugin.jar). It is where the JSObject class is located.)

When defining the Applet in the HTML, you need to add the "MAYSCRIPT"
parameter to the <APPLET> tag. e.g.

<APPLET CODE="TestingApplet.class" WIDTH="100" HEIGHT="100" MAYSCRIPT>
<PARAM NAME="initFunction" VALUE="appletLoaded">
</APPLET>


Here, I also pass a string "appletLoaded" as a parameter to the
Applet. In my testing HTML page, "appletLoaded" is in fact a
Javascript function name. Inside the Applet, when it is loaded, it
will call this function in its init() method.

I wrote a little testing program and put the HTML, Applet, and source code
here.

On that page, the "Click Me" button was originally disabled. When the
applet loads, it will call a Javascript function. And that Javascript
function will in turn enable the button.

(Since I sign my own certificate, so when you visit my site using SSL,
you will see a warning message. That is normal. Just click OK)

No comments: