Java Applets: Interacting with JavaScript Code

Java applets can invoke JavaScript functions that are present in the same html document as the applet. The following applet calls the JavaScrip doAiert() function.

import java.applet.*;

import java.net.*;

public class AppletToJavaScript extends Applet{ public void init(){

String msg = “Hello from Java (using javascript alert)”;

try {

getAppletContext().showDocument

(new URL(“javascript:doAlert(\”” + msg +”\”)”));

}

catch (MalformedURLException me) { }

}

Now consider the following html file containing a JavaScript doAiert() function and an applet.

<HTML><HEAD></HEAD><BODY>

<SCRIPT>

function doAlert(s) {

alert(s);

}

</SCRIPT>

<APPLET CODE=”AppletToJavaScript”

NAME=”myApplet” MAYSCRIPT

HEIGHT=10 WIDTH=10>

</APPLET>

</BODY>

</HTML>

A sample output is shown in Figure 16.20:

Figure 16.20: Calling a JavaScript function from an applet

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *