↑
Main Page
LiveConnect
The
JSObject
class has the following methods:
?
getMember(String name)
— Retrieves a named property of an object. Equivalent to
oObject.property
or
oObject[“property”]
in JavaScript. The returned value is a Java
Object
.
?
getSlot(int index)
— Retrieves a numbered property of an object (mostly for use with
JavaScript arrays). Equivalent to
oObject[index]
. The returned value is a Java
Object
.
?
setMember(String name, Object value)
— Sets the value of a named property.
?
setSlot(int index, Object value)
— Sets the value of a numbered property.
?
removeMember(String name)
— Removes the value of a named property.
?
call(String methodName, Object args[])
— Calls the method with the given name and
passes in the arguments contained in the array of
Object
s. The returned value is a Java
Object
.
?
eval(String code)
— Evaluates a string of JavaScript code in the context of the object; simi-
lar to JavaScript’s
eval()
function. The returned value is a Java
Object
.
?
equals(Object object)
— Determines if the object is equal to another.
One static method for
JSObject,
called
getWindow()
, accepts a Java
Applet
object as an argument
and returns a
JSObject
representation of the JavaScript
window
object.
Using
JSObject
and LiveConnect takes a little getting used to. Suppose you want to retrieve the cur-
rently loaded URL. In JavaScript, this simply requires one line of code:
var sURL = window.location.href
In Java, it becomes a bit more involved:
JSObject window = JSObject.getWindow(this);
JSObject location = (JSObject) window.getMember(“location”);
String sURL = location.getMember(“href”).toString();
The first line gets a reference to the JavaScript
window
object (the argument,
this
, represents the applet
from which the function is being called). The second line retrieves a pointer to the
location
object by
using
getMember()
. Because
getMember()
returns an
Object
, it has to be cast as a
JSObject
in order to
get access to the
JSObject
methods. The last line uses
getMember()
to get the value of
href
, which is
also returned as an
Object
, meaning that
toString()
must be called to get the string value. Obviously,
the Java code for accessing JavaScript objects is a bit verbose, but it gets the job done.
To use LiveConnect in an applet, you must import the package
netscape.javascript
. It’s not neces-
sary to distribute the package with your applet because it is built in to the Java plugin. So, just add the
following line to your
.java
file and begin coding:
import netscape.javascript.*;
549
Interacting with Plugins
21_579088 ch18.qxd 3/28/05 11:43 AM Page 549
Free JavaScript Editor
Ajax Editor
©
→