23.2. Scripting the Java Plug-inIn 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 JavaScriptExample 23-2. Scripting the Java plug-in
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. |