If you did not know that you can invoke JavaScript from within an Applet, chances are you would port most JavaScript codes to Java or, worse, resort to some exotic coding. Otherwise, you would reuse the existing codes. This post shows how to call JavaScript codes from within a Java Applet. Please note that Applet is an ancient technology, and most modern browsers no longer support it. In fact, it has been deprecated since Java 9 in 2017.
Requirements
We used the following items for this post.
- Eclipse 3.4.2
- JDK1.6.0_21
- plugin.jar (e.i., C:\Program Files\Java\jdk1.6.0_21\jre\lib\plugin.jar)
The Java Applet That Invokes JavaScript
Consider the following Java Applet codes, which extend from the Applet class. It uses JSObject, which represents a JavaScript context wherein we can invoke JavaScript codes within the Applet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.applet.Applet; import netscape.javascript.JSObject; public class Applet003 extends Applet { JSObject jsobject = null; public void start() { jsobject = JSObject.getWindow(this); // Set the value of a JavaScript variable jsobject.setMember("first_name", "karl"); // Set the value of a JavaScript variable jsobject.setMember("last_name", "san gabriel"); // Invoke the JavaScript function jsobject.eval("popFullName()"); } } |
The JSObject instance can define and initialize variables in the JavaScript context. For instance, it declares and initializes the variables first_name and last_name. Moreover, it can invoke a JavaScript function within the Applet itself. Although we could define the JavaScript function in the Applet, this post instead relies on an existing JavaScript function defined in the HTML.
The HTML For Java Applet
The only way a Java Applet can work is within the context of an HTML page. Therefore, an Applet requires a container from which to bootstrap. Consider the following codes that use a Java Applet and have a JavaScript function that our Applet invokes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <html> <head> <script> var first_name = ""; var last_name = ""; function getFullName() { return first_name + " " + last_name; } function popFullName() { alert( first_name + " " + last_name); } </script> </head> <body> <applet code="Applet003.class" width=400 height=75> </applet> </body> </html> |
Applet requires the applet tag for the browser to start it up once the page is fully loaded.
When building the Applet, make sure that plugin.jar is in the class path. Once built successfully, place the class and HTML files together in the same folder and open the page using a web browser.
With Applet already deprecated, are there alternatives similar to it? Unfortunately, there is none, at least for Java. You may want to check out WebAssembly, which is not from Oracle or based on Java.