Recipe 18.5 Making an Applet Run JavaScript


Problem

You want to invoke JavaScript from within a browser applet.

Solution

For browsers that support JavaScript, use the netscape.javascript package.

Discussion

JavaScript is Netscape's browser client-side scripting language. It can be used on the client side by Java applets in some circumstances. The Netscape browser must include the optional support for Java. The package netscape.javascript includes a class called JSObject , a top-level class analogous to java.lang.Object.

To compile such an applet, you must include the appropriate JAR file in your classpath at compile time. At runtime, the browser supplies its own version of this file since it must be present in the browser-provided classpath to be run as trusted code. The exact name of this JAR file varies. For Netscape 4.x, it is <netscapehome>/java/classes/java40.jar. Netscape 7 does not include the file in its own path, deferring to the Java Web Start (see Recipe 23.13) to provide it. In this case, look for the file netscape.jar in your Java runtime; on Mac OS X, the file is /Library/Java/Home/lib/netscape.jar.

This technique may not work with browsers such as KDE Konqueror, which use an external JVM to run applets.

Finally, the applet code in the HTML page must have the mayscript="true" attribute to grant this particular applet permission to use the JavaScript mechanism.

Still want to give it a try? Example 18-4 shows a code example using JavaScript to close the entire browser window in which the applet appears drastic and anti-social, but you can see whether it works (I've tested it on Apple's Safari browser).

Example 18-4. JScript.java
import java.applet.*; import java.awt.*; import java.awt.event.*; import netscape.javascript.*;  /* An Applet to perform JavaScript directly.  * The import of netscape.javascript.* requires a JAR file.  * EXPECT COMPILE ERROR unless you have the Netscape JAR file.  * This may be e.g., $NETSCAPEHOME/java/classes/java40.jar.  * The use of JavaScript requires <applet ... mayscript="true">  */ public class JScript extends java.applet.Applet {     JSObject jsObject;     public void init( ) {         jsObject = JSObject.getWindow(this);         Button b = new Button("CLOSE BROWSER");         b.addActionListener(new ActionListener( ) {             public void actionPerformed(ActionEvent evt) {                 jsObject.eval("window.close( )");             }         });         add(b);     } }

See Also

O'Reilly's JavaScript & DHTML Cookbook by Danny Goodman.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net