JavaScript and Embedded Objects - Including Applets (Page 3 of 15 )
Before delving into the details of applet interaction, a brief review of how to include applets in your pages is in order. Traditionally, applets are included with the <applet> tag. The tag’s code attribute is then set to the URL of the .class file containing the applet, and the height and width attributes indicate the shape of the rectangle to which the applet’s input and output are confined; for example:
<applet code="myhelloworld.class" width="400" height="100"
name="myhelloworld" id="myhelloworld">
<em>Your browser does not support Java!</em>
</applet>
Note how the <applet> tag’s name attribute (as well as id attribute) is also set. Doing so assigns the applet a convenient handle JavaScript can use to access its internals.
Although the use of <applet> is widespread, it has been deprecated under HTML 4 and XHTML. More appropriate is the <object> tag. It has a similar syntax:
<object classid="java:myhelloworld.class" width="400" height="100" name="myhelloworld" id="myhelloworld">
<em>Your browser does not support Java!</em>
</object>
Note There are some problems with the use of the <object> syntax for including applets, the least of which is lack of support in older browsers. We will use the <applet> syntax, but you should be aware that it is preferable standards-wise to use <object> whenever possible.
Initial parameters can be included inside the <applet> or <object> tag using the <param> tag, as shown here:
<applet code="myhelloworld.class" width="400" height="100"
name="myhelloworld" id="myhelloworld">
<param name="message" value="Hello world from an initial parameter!" />
<em>Your browser does not support Java!</em>
</applet>
Java Detection Before attempting to manipulate an applet from JavaScript, you must first determine whether the user’s browser is Java-enabled. Although the contents of an <applet> tag are displayed to the user whenever Java is turned off or unavailable, you still need to write your JavaScript so that you do not try to interact with an applet that is not running.
The javaEnabled() method of the Navigator object returns a Boolean indicating whether the user has Java enabled. This method was first made available in IE4 and Netscape 3, the first versions of the browsers that support JavaScript interaction with Java applets. Using a simple if statement with this method should provide the most basic Java detection, as shown here:
if ( navigator.javaEnabled() )
{
// do Java related tasks
}
else
alert("Java is off");
Once support for Java is determined, then JavaScript can be used to interact with included applets.
This chapter is from JavaScript: The Complete Reference, second edition, by Thomas Powell and Fritz Schneider, McGraw-Hill/Osborne, ISBN: 0072253576). Check it out at your favorite bookstore today.
Buy this book now. |
Next: Accessing Applets in JavaScript >>
More JavaScript Articles
More By McGraw-Hill/Osborne