Using JavaScript from Java

Having explored how to control Java from JavaScript code, we now turn to the opposite problem: how to control JavaScript from Java code. This control is accomplished primarily through the Java netscape.javascript.JSObject class, which represents a JavaScript object within a Java program. The JavaScript-to-Java capabilities described in the previous section typically work well in both Netscape and Internet Explorer. In contrast, the Java-to-JavaScript techniques described here are not as robustly supported, and you may well encounter bugs in both Netscape and IE.

The JSObject Class

All Java interactions with JavaScript are handled through an instance of the netscape.javascript.JSObject class. An instance of this class is a wrapper around a single JavaScript object. The class defines methods that allow you to read and write property values and array elements of the JavaScript object and to invoke methods of the object. Here is a synopsis of this class:

public final class JSObject extends Object { // Static method to obtain initial JSObject for applet's browser window public static JSObject getWindow(java.applet.Applet applet); public Object getMember(String name); // Read object property public Object getSlot(int index); // Read array element public void setMember(String name, Object value); // Set object property public void setSlot(int index, Object value); // Set array element public void removeMember(String name); // Delete property public Object ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.