What's New
Dev Tools
Site Map

JavaScript Interacting with Java

The different methods for JavaScript / Webpage to Interact with Java are given below:

Applet Tag Parameters to Java

Specifying the parameter in HTML

The simplest way to pass parameters from the webpage to Java is to specify parameters in the applet tag. If all that is required is a "starting value" for the Java applet, this technique should be used. In the HTML below, a parameter named "text" is passed with a value of "Ready to Being":

<applet code="JSTellJava.class" name="Name1" width=320 height=220>
<param name = "text" value = "Ready to Begin">
Browser is not Java-enabled

Picking up the HTML parameter in Java

First declare a class variable and specify a suitable default value for the parameter.

String theText = "Default"; // default text param value

Next, in the applet's init event, use the getParameter function to obtain the parameter value (always passed as a string). If the parameter was specified (i.e. is not null), then assign it to the appropriate class-level variable.

public void init() {
  String theTextParam = getParameter("text");
  if (theTextParam != null) {
    theText = theTextParam;

If the value passed was a string or integer, then an extra step to convert the String to the appropriate data type is required.

JavaScript calling Java (dynamic runtime invocation)

Code for JavaScript to call Java is given below.  Invoking Java at runtime like this is called "LiveConnect" by Netscape. The code below works for both Netscape and Internet Explorer.

First Step: Give the applet on the Webpage a Name

Using a name is preferable than referring to applet[0].

<applet code="JSTellJava.class" name="Name1" width=320 height=220>
<param name = "text" value = "Ready to Begin">

Example 1: Call a Java method

To invoke a Java method called "increaseNumber" (from JavaScript), simply prefix the public Java method with "document.appletname", as shown below.

var theIncrement;
theIncrement = form1.increment.value;

Example 2: Call a Java method and retrieve return value

It is the same as the last example, except the return value is obtained:

str = document.Name1.getString();

Example 3: Access a Public Java Variable

Although it is not good practice to directly manipulate variables in a Java class, a public Java applet variable called "delay" can be accessed in a similar manner:

document.Name1.delay = 500;


... back to JavaScript Topics

Copyright 1997-2017, Woodger Computing Inc.