Talking to applets with JavaScript

Jake Howlett, 23 Febraury 2001

Category: Java; Keywords: applet javascript java

I got asked recently "how do you get JavaScript to access the methods of a Java applet?"

Seeing as though, at the time, I was "learning" Java and always hate to have to say "I don't know" - I set about finding out. It turns out it isn't half as hard as you might imagine.

Before we start, let's look at an example. The yellow box below is a simple applet that contains just a label and a text box. Use the select box (HTML) below it to update your favourite colour.

My favourite colour is:



How does this work? Technically I think it is something to do with a Netscape invention called LiveConnect, but I won't bore you with that.

The first thing to do is create a public method in your applet that performs the actions you require. The applet above uses this code:

public void setMessageText(String message) {
txtMessage.setText( "You chose: " + message.toUpperCase() );
}


That is the hard part. Yep, that's it! All you need to do now is to create a JavaScript call to this method via the applet object. Like this:

document.applets[0].setMessageText('This text came from JavaScript');


The only other thing you need to do is add the "MAYSRIPT" attribute to the applet's tags so that is allows JavaScript to tell it what to do.

Now you may well be thinking - "What use is that!?" Wait, the possibilities are almost endless. For a start, applets can use CORBA/IIOP connections to the server to go and fetch data, not only from Domino servers. No more need to submit the document to get data from the server ;-)

All you need to do now is get up to scratch with Java applets so that you can start creating your own applets. I've attached the source file (.java) for you take a look at, but this is VERY basic. For more help you best bet is to do a search on the usual sites.

Other sources:
http://www.alphaworks.ibm.com/
http://www.looseleaf.net/Looseleaf/Forum.nsf
http://java.sun.com
http://www.notes.net/