Section 23.2. Scripting the Java Plug-in


23.2. Scripting the Java Plug-in

In addition to scripting applets, Firefox and related browsers can script the Java plug-in directly without the need for an applet. LiveConnect technology allows JavaScript code running in these browsers to instantiate Java objects and use them, even in the absence of an applet. This technique is not portable, however, and does not work in browsers such as Internet Explorer.

In browsers that support this plug-in scripting capability, the Packages object provides access to all Java packages the browser knows about. The expression Packages.java.lang refers to the java.lang package, and the expression Packages.java.lang.System refers to the java.lang.System class. For convenience, java is a shortcut for Packages.java (see the Packages and java entries in Part III). So JavaScript code might invoke a static method of this java.lang.System class as follows:

 // Invoke the static Java method System.getProperty( ) var javaVersion = java.lang.System.getProperty("java.version"); 

However, you're not limited to using static methods and predefined objects: LiveConnect allows you to use the JavaScript new operator to create new instances of Java classes. Example 23-2 shows JavaScript code that creates a new Java window and displays a message in it. Note that this JavaScript code looks almost like Java code. This code first appeared in Chapter 12, but here it is embedded in a <script> tag in an HTML file. Figure 23-1 shows the Java window created when this script is run in Firefox.

Figure 23-1. A Java window created from JavaScript


Example 23-2. Scripting the Java plug-in

 <script> // Define a shortcut to the javax.* package hierarchy var javax = Packages.javax; // Create some Java objects var frame = new javax.swing.JFrame("Hello World"); var button = new javax.swing.JButton("Hello World"); var font = new java.awt.Font("SansSerif", java.awt.Font.BOLD, 24); // Invoke methods on the new objects frame.add(button); button.setFont(font); frame.setSize(300, 200); frame.setVisible(true); </script> 

When you script the Java plug-in, your scripts are subject to the same security restrictions that untrusted applets are. A JavaScript program cannot use the java.io.File class, for example, because that would give it the power to read, write, and delete files on the client system.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

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