Java applet can communicate with Javascript in a same HTML page through a technology called LiveConnect which is supported by all major web browsers. The following figure depicts the communication between Java applet and Javascript within web browser’s environment:

liveconnect

JAR files for Java applet – Javascript communication:

The LiveConnect technology is both implemented in browser side as well as in Java side. For the Java side, it is implemented in the plugin.jar library which can be found under either following locations:

So when compiling source code which is using LiveConnect, remember to include the plugin.jar file to the classpath. But when running Java program, there is no need to include the plugin.jar file because it is already available as a part of Java runtime environment.

 

LiveConnect API:

LiveConnect API allows developers to:

The Java Plug-in is responsible for handling communication of Java - Javascript, as well as handling data type conversion on both ends.

The API is fairly simple, with only one class, JSObject, and only one exception, JSException. Both are declared under package netscape.javascript.

The following list summarizes methods of the JSObject class:



Initialization method:

 

Method Invocation:

 

Expression evaluation:

 

Member methods:

 

Array methods:

 

Data type conversion:

When invoking Javascript methods from Java applet and vice-versa, arguments and return values are automatically converted from Java data type to Javascript data type (and vice-versa) by the Java Plug-in. The following table summarizes how the conversion is applied for a particular data type:

Category

From Java data type

To Javascript data type

Numeric values

byte, character, short, int, long, float and double.

are converted to the closest available Javascript numeric type.

Strings

String

are converted to Javascript strings.

Boolean values

boolean

is converted to Javascript boolean.

Objects

Object

is converted to Javascript wrapper object.

Arrays

Java arrays are converted to Javascript pseudo-Array object

Return values

Return values from call() and eval() are always converted to Object in Java.

  
 

For more details about data type conversion between Java an Javascript, see this documentation.

 

Java Applet - Javascript Examples:

The following example briefly illustrates how to call a method, execute an expression, get value of a named member and get value of an indexed array element of Javascript from Java applet.

Source code of HTML and Javascript:

<html>
    <head>
        <title>LiveConnect - Java-Javascript communnication demo</title>
    </head>
    <body>
        <center>
            <applet id="testApplet"
                code="TestApplet.class"
                width="200" height="80"
                    >
            </applet>
        </center>
    </body>
    <script type="text/javascript">
        var coop = "Ooops!";
        this[1] = "Slot 1";

        function foo() {
            return "This is from foo()";
        }

        function bar(firstName, lastName) {
            return "Greeting " + firstName + " " + lastName + "!";
        }
    </script>
</html>
 Source code of Java applet:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;

public class TestApplet extends JApplet {

    private JButton button = new JButton("Call Javascript");
    private JLabel label = new JLabel();

    public void init() {
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(button, BorderLayout.NORTH);
        getContentPane().add(label, BorderLayout.SOUTH);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Thread runner = new Thread(new Runnable() {
                    public void run() {
                        try {
                            testLiveConnect();
                        } catch (JSException jse) {
                            // Error
                            jse.printStackTrace();
                        }
                    }
                });
                runner.start();
            }
        });
    }
    private void testLiveConnect() throws JSException {
        JSObject jso = JSObject.getWindow(this);

        // call Javascript's method foo() with no argument
        String result = (String) jso.call("foo", null);
        label.setText(result);

        // delay 2 seconds to see the result
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // call Javascript's method foo() with two arguments
        result = (String) jso.call("bar", new String[] {"Alice", "Alisa"});
        label.setText(result);
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // execute a Javascript expression
        String expression = "alert('Hi, I am from Javascript.');";
        jso.eval(expression);
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // get value of a named member from Javascript
        result = (String) jso.getMember("coop");
        label.setText(result);
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // get value of an indexed member from Javascript
        result = (String) jso.getSlot(1);
        label.setText(result);
    }
}
 

References:

LiveConnect specification

LiveConnect Javadoc

 

Other Java Applet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (LiveConnectExample.zip)LiveConnectExample.zip[LiveConnect example]1 kB