|
Accessing Java from JavaScript
|
|---|
| Java Programming Resources home.
|
| Core Web Programming home.
|
|
These examples illustrate accessing Java from JavaScript code using
Netscape's LiveConnect extensions. They only work in Netscape 3 and
4 and the Windows 95/NT versions of Internet Explorer 4.
The process is discussed in detail in Chapter 19 of
Core Web Programming, but the main examples from
that chapter are summarized below. For information on the reverse
process (accessing JavaScript from Java), see the
JavaScript from Java
thumbnail guide.
Calling Java Directly
If you don't need to construct instances or define classes, and if you
are not calling methods that throw exceptions, you can call Java code
simply via java.package.class.staticMethod(...) or
java.package.class.staticVariable.method(...).
For a small example, see
CallJava.html.
Using "Hidden" Applets to Perform Operations in Java
You can call methods in embedded applets via
document.appletName.method(...) (use all lowercase for
the appletName). For an example, see
WonderWidget.html, which uses Java to determine the client
hostname, and displays different results when clicking on a link from
different hosts (an "I'm a loyal employee" page for hosts
inside the company, an "I want a job" page for outside hosts). The
Java source is in
GetHost.java, with the two alternate resumes residing in
ResumeLoyal.html and
ResumeReal.html.
Manipulating Visible Applets
The main intended application is to call public methods of
visible applets in the page using
document.appletName.method(...) or
document.applets[index].method(...). The first approach
is shown in the section above. For an example of the latter, see
MoldSimulation.html, in which a JavaScript button tells
JavaScript to loop down all
applets in the page and calls a standard method. The applet code is in
RandomCircles.java.
More Info
For more Java and JavaScript examples, see my
Java Programming Resources page or
the source code archive for
Core Web Programming. For more info on
Core Web Programming, see the
reader reviews, the
table of contents, and a
sample chapter.