Java, Software Development

Invoking JavaScript from within an Applet

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF

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.


We used the following items for this post.

  1. Eclipse 3.4.2
  2. JDK1.6.0_21
  3. 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.

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.

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.

Invoking JavaScript from within an Applet

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.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like