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

Library 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:

    •           JRE_Home\lib (for example: c:\Program Files\Java\jdk1.7.0_03\jre\lib\plugin.jar)
    •           JDK_Home\jre\lib (for example: c:\Program Files\Java\jre7\lib\plugin.jar)

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:

    •           Access Javascript methods, variables and arrays from Java applet.
    •           Access Java applet’s public methods and variables from Javascript.
    •           Access any Java objects and its members if exposed via the applet.
    •           Passing arrays as arguments when calling Javascript methods from Java applet and vice-versa.
    •           Evaluates Javascript expression from Java applet.

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.

    • Class JSObject: acts as main interface between Java code and Javascript. It defines methods for accessing Javascript objects, methods and array elements from Java code.
    • Exception JSException: all methods of the class JSObject throw this exception if there is any error occurred in the Javascript engine. So remember to catch this exception when calling methods of the JSObject class.

The following table summarizes methods of the JSObject class:

Category

Method

Description

Initialization

static JSObject getWindow(Applet applet)

To start Java-Javascript communication, obtain a JSObject for the window that contains the given applet.

Method

Object call(String methodName, Object[] args)

 

Invokes a Javascript method with an array of arguments.

Expression

Object eval(java.lang.String s)

 

Evaluates a Javascript expression.

Member

Object getMember(String name)

 

Retrieves a named member of a Javascript object.

void setMember(String name, Object value)

 

Sets a named member of a Javascript object.

void removeMember(String name)

 

Removes a named member of a Javascript object.

Array

void setSlot(int index, Object value)

Sets an indexed member of a Javascript object.

Object getSlot(int index)

Retrieves an indexed member of a Javascript object.

 

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: http://jdk6.java.net/plugin2/liveconnect/#JS_JAVA_CONVERSIONS

 

 

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);
    }
}

For more information about how LiveConnect is applied in real life scenario, read the following articles:

References:

LiveConnect specification: http://jdk6.java.net/plugin2/liveconnect/

LiveConnect Javadoc: http://jdk6.java.net/nonav/plugin2/liveconnect/jsobject-javadoc/


Attachments:
Download this file (LiveConnectExample.zip)LiveConnectExample.zip[LiveConnect example]1 kB
Learn on Udemy Today!