Call a Java method from Javascript

From CodeCodex

Implementations[edit]

Java[edit]

You call a Java method by giving its fully qualified name. In the following snippet, the first example calls the method in the Toolkit to retrieve the screen resolution. The second example, calls a method in our Applet. NOTE: On IE4 or better, you can't call java.* methods directly from Javascript or Jscript. IE javascript can only access the public methods of an applet (a class derived from java.applet.Applet) but don't have a general access to other java classes . So the solution is simple, wrap the java.* call in a public method of a "dummy" Applet.


[Java applet]

import java.awt.*;
import java.applet.*;
public class InJava extends Applet{
  public void sayHello() {
    Graphics g = getGraphics();
    g.drawString("Hello from JAVA!", 10, 10);
    }
}

[Javascript and HTML (Netscape)]

<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {

alert("Screen Dimension\n" +
  "  width:" + 
  java.awt.Toolkit.getDefaultToolkit().getScreenSize().width +
  " height:" + 
  java.awt.Toolkit.getDefaultToolkit().getScreenSize().height);
  }
</SCRIPT>
<FORM>
<INPUT type="button" value="call Java Applet method" 
   onClick = "document.myApplet.sayHello()">
</FORM>

<INPUT type="button" value="call Java method direct" 
   onClick = "getScreenDimension()">

<APPLET CODE="InJava.class"  
        NAME="myApplet" 
        HEIGHT=100 WIDTH=100>
</APPLET>
</BODY></HTML>

Try it here

import java.awt.*;
import java.applet.*;
// (IE and Netscape ok)
public class InJava2 extends Applet{
  public int getScreenWidth() {
    return Toolkit.getDefaultToolkit().getScreenSize().width;
  }
  public int getScreenHeight() {
    return Toolkit.getDefaultToolkit().getScreenSize().height;
  }
}


[Javascript and HTML (IE and Netscape)]

<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {
   alert("Screen Dimension\r\n  width:" + 
         document.myApplet.getScreenWidth() +
         " height:" + 
        document.myApplet.getScreenHeight() );
   }
</SCRIPT>
<FORM>
<INPUT type="button" value="call JAVA" 
   onClick = "getScreenDimension()">
</FORM>
<APPLET CODE="InJava2.class"  
        NAME="myApplet" 
        HEIGHT=100 WIDTH=100>
</APPLET>
</BODY></HTML>

Try it here