Javascript is allow directly call Applet’s public methods or public variables. The Javascript consider embedded Applet as an object, by providing Applet’s an ID, Javascript can access it with

document.Applet_ID.Applet_Method()

Tutorial

In this tutorial, you will provide an ID for Applet in HTML applet tag, and use Javascript to access Applet public method.

1. Create an Applet

A simple Applet, contain a text area for display purpose.

package com.mkyong.applet;
 
import java.applet.Applet;
import java.awt.FlowLayout;
import java.awt.TextArea;
 
public class JavaScriptToJava extends Applet{
 
	TextArea textBox;
 
	public void init(){
	    setLayout(new FlowLayout());
	    textBox = new TextArea(5,40);
	    add(textBox);
	}
 
	public void appendText(String text){
		textBox.append(text);
	}	    
}

2. Create a HTML

Create a HTML file, provide Applet an Id “AppletABC”, and include a Javascript to access the Applet’s method.

<html>
 
<script language="Javascript">
function accessAppletMethod()
{
    document.AppletABC.appendText('welcome to mkyong dot com');
}
</script>
 
<head><title>Testing</title></head>
<body onload="accessAppletMethod()">
 
<h1>Javascript acess Applet method</h1>
<applet width=300 height=100 id="AppletABC" 
code="com.mkyong.applet.JavaScriptToJava.class">
</applet>
 
</body>
</html>

The alternative way is using the following method :

<script language="Javascript">
function accessAppletMethod()
{
    document.applets[0].appendText('welcome to mkyong dot com');
}
</script>

You should always prefer to use the 1st method, as it is more readable.

3. Output

When the page is loaded, Javascript’s function – “accessAppletMethod” will execute and access the Applet’s method to display the provided parameter – “Welcome to mkyong dot com” on Applet’s text area.

Javascript-access-Applet

P.S Please read article about how to Applet access Javascript method.

Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~