Chapter 15
LiveConnect Overview
- What Is LiveConnect?
- Enabling LiveConnect
- The Java Console
- Working with Wrappers
- JavaScript to Java Communication
- Java to JavaScript Communication
- Data Type Conversions
What Is LiveConnect?
In the Navigator browser, LiveConnect lets you perform the following tasks:- Use JavaScript to access Java variables, methods, classes, and packages directly.
- Control Java applets or plug-ins with JavaScript.
- Use Java code to access JavaScript methods and properties.
Enabling LiveConnect
LiveConnect is enabled by default in Navigator 1.1 and later. For LiveConnect to work, both Java and JavaScript must be enabled. To confirm they are enabled, choose Preferences from the Edit menu and display the Advanced section. To disable either Java or JavaScript, uncheck the checkboxes; if you do this, LiveConnect will not work.The Java Console
The Java Console is a Navigator window that displays Java messages. When you use the class variablesout or err in java.lang.System to output a message, the message appears in the Console. To display the Java Console, choose Java Console from the Communicator menu.
You can use the Java Console to present messages to users, or to trace the values of variables at different places in a program's execution.
For example, the following Java code displays the message "Hello, world!" in the Java Console:
public void init() {You can use the Java Console to present messages to users, or to trace the values of variables at different places in a program's execution. Note that most users probably do not display the Java Console.
System.out.println("Hello, world!")
}
Working with Wrappers
In JavaScript, a wrapper is an object of the target language data type that encloses an object of the source language. On the JavaScript side, you can use a wrapper object to access methods and fields of the Java object; calling a method or accessing a property on the wrapper results in a call on the Java object. On the Java side, JavaScript objects are wrapped in an instance of the classnetscape.javascript.JSObject and passed to Java.
When a JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to JavaScript, the runtime engine unwraps it to its original JavaScript object type. The JSObject class provides an interface for invoking JavaScript methods and examining JavaScript properties.
JavaScript to Java Communication
When you refer to a Java package or class, or work with a Java object or array, you use one of the special LiveConnect objects. All JavaScript access to Java takes place with these objects, which are summarized in the following table.| Object |
Description
|
|
| A wrapped Java object, accessed from within JavaScript code.
| |
|---|
NOTE: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See "Data Type Conversions" on page 263 for complete information.In some ways, the existence of the LiveConnect objects is transparent, because you interact with Java in a fairly intuitive way. For example, you can create a Java
String object and assign it to the JavaScript variable myString by using the new operator with the Java constructor, as follows:
var myString = new java.lang.String("Hello world")In the previous example, the variable
myString is a JavaObject because it holds an instance of the Java object String. As a JavaObject, myString has access to the public instance methods of java.lang.String and its superclass, java.lang.Object. These Java methods are available in JavaScript as methods of the JavaObject, and you can call them as follows:
myString.length() // returns 11
The Packages Object
If a Java class is not part of thejava, sun, or netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To create an instance of the HelloWorld class in redwood, you access the constructor of the class as follows:
var red = new Packages.redwood.HelloWorld()You can also access classes in the default package (that is, classes that don't explicitly name a package). For example, if the HelloWorld class is directly in the
CLASSPATH and not in a package, you can access it as follows:
var red = new Packages.HelloWorld()The LiveConnect
java, sun, and netscape objects provide shortcuts for commonly used Java packages. For example, you can use the following:
var myString = new java.lang.String("Hello world")instead of the longer version:
var myString = new Packages.java.lang.String("Hello world")
Working with Java Arrays
When any Java method creates an array and you reference that array in JavaScript, you are working with aJavaArray. For example, the following code creates the JavaArray x with ten elements of type int:
theInt = java.lang.Class.forName("java.lang.Integer")Like the JavaScript
x = java.lang.reflect.Array.newInstance(theInt, 10)
Array object, JavaArray has a length property which returns the number of elements in the array. Unlike Array.length, JavaArray.length is a read-only property, because the number of elements in a Java array are fixed at the time of creation.
Package and Class References
Simple references to Java packages and classes from JavaScript create theJavaPackage and JavaClass objects. In the earlier example about the Redwood corporation, for example, the reference Packages.redwood is a JavaPackage object. Similarly, a reference such as java.lang.String is a JavaClass object.
Most of the time, you don't have to worry about the JavaPackage and JavaClass objects--you just work with Java packages and classes, and LiveConnect creates these objects transparently.
JavaClass objects are not automatically converted to instances of java.lang.Class when you pass them as parameters to Java methods--you must create a wrapper around an instance of java.lang.Class. In the following example, the forName method creates a wrapper object theClass, which is then passed to the newInstance method to create an array.
theClass = java.lang.Class.forName("java.lang.String")
theArray = java.lang.reflect.Array.newInstance(theClass, 5)
Arguments of Type char
You cannot pass a one-character string to a Java method which requires an argument of typechar. You must pass such methods an integer which corresponds to the Unicode value of the character. For example, the following code assigns the value "H" to the variable c:
c = new java.lang.Character(72)
Controlling Java Applets
You can use JavaScript to control the behavior of a Java applet without knowing much about the internal construction of the applet. All public variables, methods, and properties of an applet are available for JavaScript access. For example, you can use buttons on an HTML form to start and stop a Java applet that appears elsewhere in the document.Referring to Applets
Each applet in a document is reflected in JavaScript asdocument.appletName, where appletName is the value of the NAME attribute of the <APPLET> tag. The applets array also contains all the applets in a page; you can refer to elements of the array through the applet name (as in an associative array) or by the ordinal number of the applet on the page (starting from zero).
For example, consider the basic "Hello World" applet in Java:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {The following HTML runs and displays the applet, and names it "HelloWorld" (with the
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
NAME attribute):
<APPLET CODE="HelloWorld.class" NAME="HelloWorld" WIDTH=150 HEIGHT=25>If this is the first applet in the document (topmost on the page), you can refer to it in JavaScript in any of the following ways:
</APPLET>
document.HelloWorldThe
document.applets["HelloWorld"]
document.applets[0]
applets array has a length property, document.applets.length, that indicates the number of applets in the document.
All public variables declared in an applet, and its ancestor classes and packages are available in JavaScript. Static methods and properties declared in an applet are available to JavaScript as methods and properties of the Applet object. You can get and set property values, and you can call methods that return string, numeric, and boolean values.
Example 1: Hello World
For example, you can modify the HelloWorld applet shown above, making the following changes:-
Override its
initmethod so that it declares and initializes a string calledmyString. -
Define a
setStringmethod that accepts a string argument, assigns it tomyString, and calls therepaintmethod. (Thepaintandrepaintmethods are inherited fromjava.awt.Component).
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
String myString;
public void init() {Making the message string a variable allows you to modify it from JavaScript. Now modify the HTML file as follows:
myString = new String("Hello, world!");
}
public void paint(Graphics g) {
g.drawString(myString, 25, 20);
}
public void setString(String aString) {
myString = aString;
repaint();
}
}
- Add a form with a button and a text field.
-
Make the
onClickevent handler for the button call thesetStringmethod of HelloWorld with the string from the text field as its argument.
<APPLET CODE="HelloWorld1.class" NAME="Hello" WIDTH=150 HEIGHT=25>
</APPLET>
<FORM NAME="form1">When you compile the HelloWorld applet, and load the HTML page into Navigator, you initially see "Hello, World!" displayed in the gray applet panel. However, you can now change it by entering text in the text field and clicking on the button. This demonstrates controlling an applet from JavaScript.
<INPUT TYPE="button" VALUE="Set String"
onClick="document.HelloWorld.setString(document.form1.str.value)">
<BR>
<INPUT TYPE="text" SIZE="20" NAME="str">
</FORM>
Example 2: Flashing Color Text Applet
As another slightly more complex example, consider an applet that displays text that flashes in different colors. A text field lets you enter new text to flash and a push button changes the flashing text to your new value. This applet is shown in Figure 15.1.
Figure 15.1 Flashing text applet
<APPLET CODE="colors.class" WIDTH=500 HEIGHT=60 NAME="colorApp">
</APPLET>
<FORM NAME=colorText>
<P>Enter new text for the flashing display:
<INPUT TYPE="text"
NAME="textBox"
LENGTH=50>
<P>Click the button to change the display:
<INPUT TYPE="button"
VALUE="Change Text"
onClick="document.colorApp.setString(document.colorText.textBox.value)">
</FORM>This applet uses the public method
setString to specify the text for the flashing string that appears. In the HTML form, the onClick event handler of the button lets a user change the "Hello, world!" string that the applet initially displays by calling the setString method.
In this code, colorText is the name of the HTML form and textBox is the name of the text field. The event handler passes the value that a user enters in the text field to the setString method in the Java applet.
Controlling Java Plug-ins
Each plug-in in a document is reflected in JavaScript as an element in theembeds array. For example, the following HTML code includes an AVI plug-in in a document:
<EMBED SRC=myavi.avi NAME="myEmbed" WIDTH=320 HEIGHT=200>If this HTML defines the first plug-in in a document, you can access it in any of the following ways:
document.embeds[0]If the plug-in is associated with the Java class
document.embeds["myEmbed"]
document.myEmbed
netscape.plugin.Plugin, you can access its static variables and methods the way you access an applet's variables and methods.
The embeds array has a length property, document.embeds.length, that indicates the number of plug-ins embedded in the document.
The Plug-in Guide contains information on:
Java to JavaScript Communication
If you want to use JavaScript objects in Java, you must import thenetscape.javascript package into your Java file. This package defines the following classes:
-
netscape.javascript.JSObjectallows Java code to access JavaScript methods and properties. -
netscape.javascript.JSExceptionallows Java code to handle JavaScript errors. -
netscape.plugin.Pluginallows client-side JavaScript and applets to manipulate a plug-in.
CLASSPATH of the JDK compiler in either of the following ways:
-
Create a
CLASSPATHenvironment variable to specify the path and name of .jar or .zip file. -
Specify the location of .jar or .zip file when you compile by using the
-classpathcommand line parameter.
java40.jar file in the Program\Java\Classes directory beneath the Navigator directory. You can specify an environment variable in Windows NT by double-clicking the System icon in the Control Panel and creating a user environment variable called CLASSPATH with a value similar to the following:
D:\Navigator\Program\Java\Classes\java40.jarSee the Sun JDK documentation for more information about
CLASSPATH.
NOTE: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See "Data Type Conversions" on page 263 for complete information.
Using the LiveConnect Classes
All JavaScript objects appear within Java code as instances ofnetscape.javascript.JSObject. When you call a method in your Java code, you can pass it a JavaScript object as one of its argument. To do so, you must define the corresponding formal parameter of the method to be of type JSObject.
Also, any time you use JavaScript objects in your Java code, you should put the call to the JavaScript object inside a try...catch statement which handles exceptions of type netscape.javascript.JSException. This allows your Java code to handle errors in JavaScript code execution which appear in Java as exceptions of type JSException.
Accessing JavaScript with JSObject
For example, suppose you are working with the Java class calledJavaDog. As shown in the following code, the JavaDog constructor takes the JavaScript object jsDog, which is defined as type JSObject, as an argument:
import netscape.javascript.*;Notice that the
public class JavaDog
{
public String dogBreed;
public String dogColor;
public String dogSex;
// define the class constructor
public JavaDog(JSObject jsDog)
{
// use try...catch to handle JSExceptions here
this.dogBreed = (String)jsDog.getMember("breed");
this.dogColor = (String)jsDog.getMember("color");
this.dogSex = (String)jsDog.getMember("sex");
}
}
getMember method of JSObject is used to access the properties of the JavaScript object. The previous example uses getMember to assign the value of the JavaScript property jsDog.breed to the Java data member JavaDog.dogBreed.
NOTE: A more realistic example would place the call toTo get a better sense of howgetMemberinside atry...catchstatement to handle errors of typeJSException. See "Handling JavaScript Exceptions in Java" on page 259 for more information.
getMember works, look at the definition of the custom JavaScript object Dog:
function Dog(breed,color,sex) {You can create a JavaScript instance of
this.breed = breed
this.color = color
this.sex = sex
}
Dog called gabby as follows:
gabby = new Dog("lab","chocolate","female")If you evaluate
gabby.color, you can see that it has the value "chocolate". Now suppose you create an instance of JavaDog in your JavaScript code by passing the gabby object to the constructor as follows:
javaDog = new Packages.JavaDog(gabby)If you evaluate
javaDog.dogColor, you can see that it also has the value "chocolate", because the getMember method in the Java constructor assigns dogColor the value of gabby.color.
Handling JavaScript Exceptions in Java
When JavaScript code called from Java fails at run time, it throws an exception. If you are calling the JavaScript code from Java, you can catch this exception in atry...catch statement. The JavaScript exception is available to your Java code as an instance of netscape.javascript.JSException. JSException is a Java wrapper around any exception type thrown by JavaScript, similar to the way that instances of JSObject are wrappers for JavaScript objects.
Use JSException when you are evaluating JavaScript code in Java. If the JavaScript code is not evaluated, either due to a JavaScript compilation error or to some other error that occurs at run time, the JavaScript interpreter generates an error message that is converted into an instance of JSException.
For example, you can use a try...catch statement such as the following to handle LiveConnect exceptions:
try {In this example, the
global.eval("foo.bar = 999;");
} catch (Exception e) {
if (e instanceof JSException) {
jsCodeFailed()";
} else {
otherCodeFailed();
}
}
eval statement fails if foo is not defined. The catch block executes the jsCodeFailed method if the eval statement in the try block throws a JSException; the otherCodeFailed method executes if the try block throws any other error.
Accessing Client-Side JavaScript
Now let's look specifically at using Java to access client-side JavaScript. The author of an HTML page must permit an applet to access JavaScript by specifying theMAYSCRIPT attribute of the <APPLET> tag. This prevents an applet from accessing JavaScript on a page without the knowledge of the page author. Attempting to access JavaScript from an applet that does not have the MAYSCRIPT attribute generates an exception. The MAYSCRIPT tag is needed only for Java to access JavaScript; it is not needed for JavaScript to access Java.
Getting a Handle for the JavaScript Window
Before you can access JavaScript in Navigator, you must get a handle for the Navigator window. Use thegetWindow method in the class netscape.javascript.JSObject to get a window handle, passing it the Applet object.
For example, if win is a previously-declared variable of type JSObject, the following Java code assigns a window handle to win:
public class myApplet extends Applet {
public void init() {
JSObject win = JSObject.getWindow(this);
}
}
Accessing JavaScript Objects and Properties
ThegetMember method in the class netscape.javascript.JSObject lets you access JavaScript objects and properties. Call getWindow to get a handle for the JavaScript window, then call getMember to access each JavaScript object in a containership path in turn. Notice that JavaScript objects appear as instances of the class netscape.javascript.JSObject in Java.
For example, the following Java code allows you to access the JavaScript object document.testForm through the variable myForm:
public void init() {Note that you could use the following lines in place of
win = JSObject.getWindow(this);
myForm=win.eval("document.testForm")
}
myForm=win.eval("document.testForm"):
JSObject doc = (JSObject) win.getMember("document");If the JavaScript object
JSObject myForm = (JSObject) doc.getMember("testForm");
document.testForm.jazz is a checkbox, the following Java code allows you to access its checked property:
public void init() {
win = JSObject.getWindow(this);
JSObject doc = (JSObject) win.getMember("document");
JSObject myForm = (JSObject) doc.getMember("testForm");
JSObject check = (JSObject) myForm.getMember("jazz");
Boolean isChecked = (Boolean) check.getMember("checked");
}
Calling JavaScript Methods
Theeval method in the class netscape.javascript.JSObject let you evaluate an arbitrary JavaScript expression. Use getWindow to get a handle for the JavaScript window, then use eval to access a JavaScript method.
Use the following syntax to call JavaScript methods:
JSObject.getWindow().eval("expression")
expression is a JavaScript expression that evaluates to a JavaScript method call.
For example, the following Java code uses eval to call the JavaScript alert method when a MouseUp event occurs:
public void init() {
JSObject win = JSObject.getWindow(this);
}
public boolean mouseUp(Event e, int x, int y) {Another way to call JavaScript methods is with the
win.eval("alert(\"Hello world!\");");
return true;
}
call method of JSObject. Use the following to call a JavaScript method from Java when you want to pass Java objects as arguments:
JSObject.call(methodName, argArray)where
argArray is an Array of Java objects used to pass arguments to the JavaScript method.
If you want to pass primitive values to a JavaScript method, you must use the Java object wrappers (such as Integer, Float, and Boolean), and then populate an Array with such objects.
Example: Hello World
Returning to the HelloWorld example, modify thepaint method in the Java code so that it calls the JavaScript alert method (with the message "Painting!") as follows:
public void paint(Graphics g) {Then add the
g.drawString(myString, 25, 20);
JSObject win = JSObject.getWindow(this);
String args[] = {"Painting!"};
win.call("alert", args);
}
MAYSCRIPT attribute to the <APPLET> tag in the HTML page, recompile the applet, and try it. Each time the applet is painted (when it is initialized, when you enter a new text value, and when the page is reloaded) a JavaScript alert box is displayed. This is a simple illustration of calling JavaScript from Java.
This same effect could be achieved with the following:
public void paint(Graphics g) {
g.drawString(myString, 25, 20);
JSObject win = JSObject.getWindow(this);
win.eval("alert('Painting')");
}
NOTE: You may have to reload the HTML page by choosing Open Page from the File menu instead of clicking the Reload button, to ensure that the applet is re- initialized.
Calling User-Defined Functions
You can also call user-defined functions from a Java applet. For example, add the following function to the<HEAD> of the HTML page with the HelloWorld applet:
<SCRIPT>This simple function displays an alert dialog box containing the name and version of the client software being used. Then modify the
function test() {
alert("You are using " + navigator.appName + " " +
navigator.appVersion)
}
</SCRIPT>
init method in your Java code similarly to how you modified paint:
public void init() {Notice that
myString = new String("Hello, world!")
JSObject win = JSObject.getWindow(this)
String args2[] = {""}
win.call("test", args2)
}
args2 is declared as an array with no elements, even though the method does not take any arguments. When you recompile the applet and reload the HTML page (and re-initialize the applet), a JavaScript alert dialog box will display the version of Navigator you are running. This is a simple illustration of calling a user-defined function from Java.
Data Type Conversions
Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. These conversions are described in the following sections:JavaScript to Java Conversions
When you call a Java method and pass it parameters from JavaScript, the data types of the parameters you pass in are converted according to the rules described in the following sections:- Number Values
- Boolean Values
- String Values
- Undefined Values
- Null Values
- JavaArray and JavaObject objects
- JavaClass objects
- Other JavaScript objects
netscape.javascript.JSObject are always converted to instances of java.lang.Object. The rules for converting these return values are also described in these sections.
For example, if JSObject.eval returns a JavaScript number, you can find the rules for converting this number to an instance of java.lang.Object in "Number Values" on page 264.
Number Values
When you pass JavaScript number types as parameters to Java methods, Java converts the values according to the rules described in the following table:
| Java parameter type |
Conversion rules
The exact value is transferred to Java without rounding and without a loss of magnitude or sign.
|
|
|
|
| |
|---|
java.lang.String, the number is converted to a string. Use the == operator to compare the result of this conversion with other string values.
Boolean Values
When you pass JavaScript Boolean types as parameters to Java methods, Java converts the values according to the rules described in the following table:
| Java parameter type |
Conversion rules
|
|
|
|
| |
|---|
java.lang.String, the Boolean is converted to a string. Use the == operator to compare the result of this conversion with other string values.
String Values
When you pass JavaScript string types as parameters to Java methods, Java converts the values according to the rules described in the following table:
| Java parameter type |
Conversion rules
A JavaScript string is converted to an instance of All values are converted to numbers as described in ECMA-262.
|
| |
|---|
Undefined Values
When you pass undefined JavaScript values as parameters to Java methods, Java converts the values according to the rules described in the following table:
| Java parameter type |
Conversion rules
The value is converted to an instance of java.lang.String whose value is the string "undefined".
|
|
| |
|---|
java.lang.String, the undefined value is converted to a string. Use the == operator to compare the result of this conversion with other string values.
Null Values
When you pass null JavaScript values as parameters to Java methods, Java converts the values according to the rules described in the following table:
| Java parameter type |
Conversion rules
|
|
|
| |
|---|
JavaArray and JavaObject objects
In most situations, when you pass a JavaScriptJavaArray or JavaObject as a parameter to a Java method, Java simply unwraps the object; in a few situations, the object is coerced into another data type according to the rules described in the following table:
unwrappedObject instanceof parameterType
JavaClass objects
When you pass a JavaScriptJavaClass object as a parameter to a Java method, Java converts the object according to the rules described in the following table:
| Java parameter type |
Conversion rules
|
|
The
| The object is unwrapped and either of the following situations occur: |
|---|
Other JavaScript objects
When you pass any other JavaScript object as a parameter to a Java method, Java converts the object according to the rules described in the following table:
Java to JavaScript Conversions
Values passed from Java to JavaScript are converted as follows:- Java byte, char, short, int, long, float, and double are converted to JavaScript numbers.
- A Java boolean is converted to a JavaScript boolean.
-
An object of class
netscape.javascript.JSObjectis converted to the original JavaScript object. -
Java arrays are converted to a JavaScript pseudo-Array object; this object behaves just like a JavaScript
Arrayobject: you can access it with the syntaxarrayName[index](whereindexis an integer), and determine its length witharrayName.length. - A Java object of any other class is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object:
-
Converting this wrapper to a string calls thetoStringmethod on the original object. -
Converting to a number calls thedoubleValuemethod, if possible, and fails otherwise. -
Converting to a boolean in JavaScript 1.3 returns false if the object is null, and true otherwise. -
Converting to a boolean in JavaScript 1.2 and earlier versions calls thebooleanValuemethod, if possible, and fails otherwise.
String objects also correspond to JavaScript wrappers. If you call a JavaScript method that requires a JavaScript string and pass it this wrapper, you'll get an error. Instead, convert the wrapper to a JavaScript string by appending the empty string to it, as shown here:
var JavaString = JavaObj.methodThatReturnsAString();
var JavaScriptString = JavaString + "";
Table of Contents | Previous | Next | Index
Last Updated: 05/27/99 21:21:44
