Sometimes there is a need to call JavaScript function from an applet.As both are the parts of an HTML page, in case we want our applet to communicate with browser then we call javascript function and then javascript communicate with browser.
To call javascript function we first need plugin.jar which contains the classes needed for an applet to call javascript functions.It should be set in our classpath.
(plugin .jar is found lib directory – say “C:\Program Files\Java\jre6\lib” ).
Here is sample code which calls java script function ( javaScriptFunction() in this case ) from an applet using JSObject :
Applet (Java code) :
import java.applet.*; import netscape.javascript.JSException; import netscape.javascript.JSObject; public class Main extends Applet { @Override public void init() { try { //this returns a new JSObject for the window containing the applet JSObject window = JSObject.getWindow(this); /***@param 1 :javaScript function name to be call ( javaScriptFunction() in this case ) @param 2 :some parameter need to be send to the javascript function ( it accepts object[] ). it will call the javascript function. ***/ window.call("javaScriptFunction", null); } catch (JSException jse) { //JSException is thrown when javascript returns an error. jse.printStackTrace(); } } }
——————————————————————————–
HTML :
<HTML> <HEAD> <SCRIPT> //this function called from an applet. function javaScriptFunction() { alert("Call From an Applet"); } </SCRIPT> </HEAD> <BODY> <APPLET CODE="Main.class" NAME="myApplet" MAYSCRIPT HEIGHT=200 WIDTH=200> </APPLET> </BODY> </HTML>