Documentation

Invoking Applet Methods From JavaScript Code
Trail: Deployment
Lesson: Java Applets
Section: Doing More With Applets

Invoking Applet Methods From JavaScript Code

JavaScript code on a web page can interact with Java applets embedded on the page. JavaScript code can perform operations such as the following:

The LiveConnect Specification describes details about how JavaScript code communicates with Java code.

Security warnings are shown when JavaScript code makes calls to a Java applet. To suppress these warnings, add the Caller-Allowable-Codebase attribute to the JAR file manifest. Specify the location of the JavaScript code that is allowed to make calls to the applet. See JAR File Manifest Attributes for Security for information about the Caller-Allowable-Codebase attribute.

This topic explores JavaScript code to Java applet communication using the Math applet example. The MathApplet class and supporting Calculator class provide a set of public methods and variables. The JavaScript code on the web page invokes and evaluates these public members to pass data and retrieve calculated results.

Math Applet and Related Classes

Here is the source code for the MathApplet class. The getCalculator method returns a reference to the Calculator helper class.

 
package jstojava;
import java.applet.Applet;

public class MathApplet extends Applet{

    public String userName = null;
         
    public String getGreeting() {
        return "Hello " + userName;
    }
    
    public Calculator getCalculator() {
        return new Calculator();
    } 
    
    public DateHelper getDateHelper() {
        return new DateHelper();
    }
    
    public void printOut(String text) {
        System.out.println(text);
    }
}

The methods in the Calculator class let the user set two values, add numbers, and retrieve the numbers in a range.


package jstojava;

public class Calculator {
    private int a = 0;
    private int b = 0; // assume b > a
    
    public void setNums(int numA, int numB) {
        a = numA;
        b = numB;
    }
    
    public int add() {
        return a + b;
    }
    
    public int [] getNumInRange() {    
        int x = a;
        int len = (b - a) + 1;
        int [] range = new int [len];
        for (int i = 0; i < len; i++) {
            range[i]= x++;
            System.out.println("i: " + i + " ; range[i]: " + range[i]);
        }
        return range;
    }
}

The getDate method of the DateHelper class returns the current date.


package jstojava;
import java.util.Date;
import java.text.SimpleDateFormat;

public class DateHelper {
    
    public static String label = null;
        
    public String getDate() {
        return label + " " + new SimpleDateFormat().format(new Date());
    }

}

Deploying the Applet

Deploy the applet in a web page, AppletPage.html When deploying the applet, make sure that you specify an id for the applet. The applet id is used later to obtain a reference to the applet object.

<script src=
  "https://www.java.com/js/deployJava.js"></script>
<script>
    <!-- applet id can be used to get a reference to
    the applet object -->
    var attributes = { id:'mathApplet',
        code:'jstojava.MathApplet',  width:1, height:1} ;
    var parameters = { jnlp_href: 'math_applet.jnlp'} ;
    deployJava.runApplet(attributes, parameters, '1.6');
</script>

Next, add some JavaScript code to the AppletPage.html web page. The JavaScript code can use the applet id as a reference to the applet object and invoke the applet's methods. In the example shown next, the JavaScript code sets the applet's public member variables, invokes public methods, and retrieves a reference to another object referenced by the applet (Calculator). The JavaScript code is able to handle primitive, array, and object return types.

<script language="javascript">
    function enterNums(){
        var numA = prompt('Enter number \'a\'?','0');
        var numB = prompt(
            'Enter number \'b\' (should be greater than number \'a\' ?','1');
        // set applet's public variable
        mathApplet.userName = "John Doe";

        // invoke public applet method
        var greeting = mathApplet.getGreeting();

        // get another class referenced by applet and
        // invoke its methods
        var calculator = mathApplet.getCalculator();
        calculator.setNums(numA, numB);

        // primitive datatype returned by applet
        var sum = calculator.add();

        // array returned by applet
        var numRange = calculator.getNumInRange();

        // check Java console log for this message
        mathApplet.printOut("Testing printing to System.out");

        // get another class, set static field and invoke its methods
        var dateHelper = mathApplet.getDateHelper();
        dateHelper.label = "Today\'s date is: ";
        var dateStr = dateHelper.getDate();
        <!-- ... -->
</script>

The Math applet displays the following results on the web page when the number a = 0 and b = 5:

Results of JavaScript to Java Communication

Hello John Doe

a = 0 ; b = 5

Sum: 5

Numbers in range array: [ 0, 1, 2, 3, 4, 5 ]

Today's date is: 5/28/13 4:12 PM //shows current date

Open AppletPage.html in a browser to view the Math applet.


Note:  If you don't see the applet running, you need to install at least the Java SE Development Kit (JDK) 6 update 10 release.

Note:  If you don't see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.

Check security restrictions placed on applets invoked by JavaScript code.

Download source code for the Invoking Applet Methods From JavaScript Code example to experiment further.


Previous page: Invoking JavaScript Code From an Applet
Next page: Handling Initialization Status With Event Handlers