Main Page

HTML document

Here’s an example applet that makes use of the LiveConnect package:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.HeadlessException;
import netscape.javascript.*;
public class ExampleApplet3 extends Applet {
public ExampleApplet3() throws HeadlessException {
super();
}
public void paint(Graphics g) {
JSObject window = JSObject.getWindow(this);
JSObject document = (JSObject) window.getMember(“document”);
JSObject location = (JSObject) window.getMember(“location”);
g.drawString(“Title: “ + document.getMember(“title”), 10, 20);
g.drawString(“URL: “ + location.getMember(“href”), 10, 40);
window.eval(“getMessageFromApplet(\”Hello from the Java applet!\”)”);
}
}
This applet uses the applet’s
paint()
method to interact with the page’s JavaScript. The method begins
by getting references to the window, document, and location objects using the methodology discussed
previously. Next, the applet draws the title of the page (retrieved from
document.title
) and the URL
of the page (from
location.href
) onto the applet canvas.
Lastly, the
window
’s
eval()
method is used to evaluate a call to
getMessageFromApplet()
, which is a
JavaScript function that must be defined in the HTML page containing the applet. If the function doesn’t
exist when the applet is initialized, then a
JSException
occurs.
When including an applet that uses the LiveConnect package, you must set a special parameter to allow
it access to the HTML document. The parameter ’s name is
mayscript
, and it should be set to
true
:
<object type=”application/x-java-applet” code=”ExampleApplet3.class”
width=”100” height=”100” id=”ExampleApplet”>
<param name=”mayscript” value=”true” />
</object>
If you are using the old
<applet/>
element, then just include
mayscript
as an attribute:
<applet code=”ExampleApplet3.class” mayscript=”mayscript”
width=”100” height=”100” name=”ExampleApplet”>
</applet>
550
Chapter 18
21_579088 ch18.qxd 3/28/05 11:43 AM Page 550


JavaScript EditorFree JavaScript Editor     Ajax Editor


©