Share this page 

Access Java variables from JavascriptTag(s): Javascript interaction

Java variables can be used by giving the fully qualified name. In Java, the variable must be declared as "public". To be compatible Netscape AND MSIEv4, the preferred way is to use special "access method" to read Java variables (only String or integer).

[Java applet]

import java.awt.*;
import java.applet.*;
public class InJava3 extends Applet{
  public int     iJava = 123;
  public String  sJava = "String from JAVA";

  public int getIntJava() {
      return iJava;
  public String getStringJava() {
     return sJava;

[Javascript and HTML]

function JavaSays() {
   alert("Java says\n the value of iJava is :" +
         document.myApplet.getIntJava() + "\n" +
         "and sJava is :" +      
<INPUT type="button" value="Java says" 
   onClick = "JavaSays();">
<APPLET CODE="InJava3.class"  
        HEIGHT=0 WIDTH=0>
Try it here

Remember that IE4 can access only attributes and methods from a class derived from java.applet.Applet. If you want to call a method or use an attribute in another class, you have to create a method in your applet class that calls the other class's method.