Embedding Applets in Java script - Java Script

The oldest form of plugin,the Java applet has recently been redefined to work with the generic browser plugin framework. Previously,applets had to be loaded using the <applet/> element. HTML 4.0 deprecated <applet/>,favoring <object/> as the sole means for embedding plugins.To aid in this move, Sun Microsystems created the Java Plugin, which is included as part of the Java Runtime Environment (JRE) .

Embedding applets

Embedding an applet requires you to use the nonstandard code property of <object/> to specify the class to load. Although all browsers should work when using data for the same purpose,the reality is that support isn’t yet universal. So,in the interest of cross-browser compatibility,it’s best to use code in this way:

Note the mime type for Java applets is application/x-java-applet.By specifying this, you are sure that the browser will use the most appropriate (and available) version of the Java plugin.You can optionally specify the exact version required by adding it to the end of the mime type. For example, to specify version 1.4.2 (from JRE 1.4.2), add “jpi-version=1.4.2”:

In this mime type, JPI is short for Java PlugIn and it ensures that the applet is not run unless the plugin on the user’s computer is exactly equal to version 1.4.2.So even if the user has version 1.4.3, the applet does not run. For this reason,it’s best to omit the plugin version to avoid any annoyance for your users.

The applet class can be contained within a JAR (Java Archive) file. In that case, specify the JAR file by using the archive attribute:

To support Netscape Navigator 4.x, you use the original <applet/> element.To ensure that the code works in all browsers, you can embed <applet/> inside of <object/>(similar to the way you can place <embed/> inside of <object/>).However, doing so requires the use of the IE-proprietary <comment/> element. Although Mozilla and other browsers ignore content inside of <object/>, IE doesn’t, and could end up rendering two copies of the same applet. Inserting the <comment/> element tells IE to ignore the extra content:

Referencing applets in JavaScript

After an applet has been included in an HTML page, you need a way to access it via JavaScript. Traditionally,applets were referenced through the document.applets collection, which indexed all <applet/> elements by their name attribute and position in the document (similar to document.forms and document.frames).For example, to get a reference to an applet with the name attribute set to “ExampleApplet”, you could do the following:

var oApplet = document.applets[“ExampleApplet”];

However, if you use the <object/> element to embed applets, the document.applets collection doesn’t include it. When using <object/>, you can access the applet using document.getElementById():

var oApplet = document.getElementById(“ExampleApplet”);

If you are using both <object/> and <applet/> for compatibility with older browsers, you should use a function to determine the appropriate method:

After you have a reference to the applet, you can actually access all the applet’s public methods directly from JavaScript,such as:

oApplet.appletPublicMethod();

This opens up all kinds of functionality to JavaScript by using a Java applet as a host environment; JavaScript can control anything that can be done within the applet.

Writing applets

To write a Java applet, you must first download the Java Development Kit (JDK) from Sun’s Web site (http://java.sun.com/j2se/). It is up to you whether you use a development environment or a plain text editor to write the applet, but all applets have one thing in common: they must inherit from java.applet.Applet.(You can, however, create a Swing-based Java applet by inheriting from javax.swing.JApplet, which inherits from java.applet.Applet).

Here’s a small example applet:

This applet simply displays the text “Hello World!” on the applet. The paint() method controls what is displayed when the applet is first loaded, and it receives a Graphics object as its sole argument. The Graphics object is a representation of the visual area of the applet with methods to draw onto the applet, such as drawString(),which draws the given text at the x and y coordinates specified.

The applet defined previously also has a private property called message, which is initialized to “Hello World!” This property can be changed by calling setMessage(), which is accessible from JavaScript because it is a public method. The method simply assigns the specified string to the message property, then calls repaint(), which clears the display of the applet and calls the paint() method again.

Applets only require a default constructor (which throws a HeadlessException if the operating system doesn’t have a graphical interface). If the applet’s purpose is solely to provide Java functionality to JavaScript, you can just add public methods and set the applet to a width and height of 0 in the HTML.

If, however, the applet is to display something, you most likely need to defined a paint() method.

After the applet is defined and saved in a file with a .java extension,compile the file using the javac utility from the command line:

javac ExampleApplet.java

This command creates a file with a .class extension (the previous example creates
ExampleApplet.class). The .class file must be placed in a Web server directory to allow HTML pages to access it.

JavaScript-to-Java communication

Now that you have an applet with a public method, you can include it in a Web page and access it via JavaScript.The following example uses ExampleApplet from the previous section and shows how JavaScript can be used to change the message displayed in the applet:

This example presents the user with a text box where a new message can be entered. When the user clicks the Set Message button, it calls the changeAppletMessage() function, which gets a reference to the applet and retrieves the text from the text box. Then, the function calls the applet’s setMessage() method, passing in the entered text.The message displayed in the applet changes from “Hello World!” to whatever the user enters (sometimes this happens quickly, sometimes slowly).

Type conversion

Although JavaScript-to-Java communication is a powerful tool for developers, it is not without its issues. In the previous example, a string was passed from JavaScript to a Java method without issue.That’s because the JavaScript String object maps directly to the Java String object. The same is true for any primitive value in JavaScript because they all have equivalent primitive types in Java. You can run into trouble when trying to pass objects into a Java method because no equivalent class exists. For this reason,it’s always best that any method you create for use with JavaScript accept only primitive values.

Handling Java exceptions

Exceptions are much more common in Java than in JavaScript,so you must be aware when they could possibly occur. When accessing an applet method that could cause an error,you can prepare by wrapping the call in try..catch statement. Yes, the JavaScript try..catch statement catches exceptions thrown by an applet.

Suppose you change the ExampleApplet to throw an error if setMessage() is passed a zero-length string, such as:

It would then be possible to catch a thrown error using the JavaScript try..catch statement:

Because of differences in browsers, it’s not easy to say what will be returned by oError. Internet Explorer returns a JavaScript object representing the Java exception, whereas Mozilla returns the Java exception object itself. The two browsers have different ways to access the error information: In IE, the oError.message property displays the Java exception message; in Mozilla, the toString() method returns a string of Java exceptions, but doesn’t contain the original exception method. In most cases, however, it’s enough to know that an error occurred.

Security restrictions

Although Java is more powerful than JavaScript,it doesn’t have free reign over the browser when included in a Web page. Java applets must follow a strict set of rules set out by the browser.(The rules are different in every browser, although several rules are fairly common.) This behavior is called sandboxing.

First, applets are not allowed access to the user’s file system. This prevents a major security problem if a malicious applet writer gets an unsuspecting user to open a page containing the applet.By default, this isn’t possible.

Second, applets aren’t allowed to access resources across domains. This is the same security restriction placed on the XML HTTP requests discussed earlier.

It is possible to get around these restrictions by digitally signing the applet. When an applet is signed, a dialog is presented to the user asking whether the signature is valid and, in turn, whether the applet should be allowed enhanced privileges not available otherwise. If the signature is accepted, the restrictions mentioned previously are lifted.

Java-to-JavaScript communication

Not only can JavaScript access methods contained in a Java applet, an applet can actually access JavaScript objects and functions as well by using LiveConnect. LiveConnect was mentioned earlier as a way for JavaScript to access Java objects, but it can also be used to more closely integrate applets and JavaScript using a special Java package: netscape.javascript.

This package contains two classes: JSObject, which is a Java representation of a JavaScript object, and JSException,which represents a JavaScript error. However, the JSObject is really the focus of Java-to- JavaScript communication.
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 Objects. The returned value is a Java Object.
  • eval(String code)— Evaluates a string of JavaScript code in the context of the object;similar 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 currently loaded URL. In JavaScript, this simply requires one line of code:

var sURL = window.location.href

In Java, it becomes a bit more involved:

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 necessary 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.*;

Here’s an example applet that makes use of the LiveConnect package:

This applet uses the applet’s paint() method to interact with the page’s JavaScript. The method begins by getting references to the window, document, and location objects using the methodology discussed previously. Next, the applet draws the title of the page(retrieved from document.title) and the URL of the page (from location.href) onto the applet canvas.

Lastly, the window’s eval() method is used to evaluate a call to getMessageFromApplet(),which is a JavaScript function that must be defined in the HTML page containing the applet.If the function doesn’t exist when the applet is initialized, then a JSException occurs.

When including an applet that uses the LiveConnect package, you must set a special parameter to allow it access to the HTML document. The parameter’s name is mayscript, and it should be set to true:

If you are using the old <applet/> element, then just include mayscript as an attribute:

Back to the example,the getMessageFromApplet() function does nothing more than display the argument that was passed. Here’s the complete HTML code for the page:

When this page is loaded, the applet displays the page title (Applet Example) and the URL you are viewing the example from. Then, you should see an alert displaying the message “Applet says:

Hello from the Java applet!”

You can also use call() to execute getMessageFromApplet():

Because getMessageFromApplet() is a global function, it’s considered a method of window and, therefore, can be called using the call() method.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics