How to call Javascript function from Java applet
- Details
- Written by Nam Ha Minh
- Last Updated on 09 August 2019   |   Print Email
1. The steps to invoke Javascript function
The typical steps to call a Javascript function from a Java applet are as follows:- Import the package netscape.javascript. This package contains only two classes: JSObject and JSException and it is provided by the plugin.jar library which resides in the JRE_HOME\lib directory or in JDK_HOME\jre\lib directory. So we have to add path of the plugin.jar file to the compilation classpath.
- Obtain an instance of the JSObjectclass for the applet:
JSObject jsObj = JSObject.getWindow(applet);
Where applet is the instance of the applet class which extends from java.applet.Applet class. The JSObject class defines principal methods which allow Java applet accessing Javascript variables and methods. - Assuming we want to invoke a Javascript method add(a, b) which returns sum of two numbers, write the following code:
Object result = jsObj.call("add", new Integer[] {17, 28});
The call() method’s first parameter is the name of Javascript method, and the second one is an array of Object for the Javascript method’s parameters. The call() method always returns an Object as return value of the invoked method (null if the Javascript method does not return anything).
NOTES:
- When passing parameters to Javascript method, the Java data types are converted to Javascript equivalents, and the type of return value from Javascript is converted to Java equivalent.
- All methods of the JSObject class throw JSExceptionso we have to catch this exception.
2. A complete Java applet invoking Javascript method example
The following example creates an applet looks like this:This applet shows two text fields which allow users entering two numbers. On clicking the Sum button, the applet will call a Javascript function to calculate the sum and show result in a message dialog like this:import java.awt.*; import java.awt.event.*; import javax.swing.*; import netscape.javascript.*; /** * A simple Java applet that demonstrates invoking a Javascript method */ public class SimpleApplet extends JApplet { private JTextField textA = new JTextField(5); private JTextField textB = new JTextField(5); private JButton button = new JButton("Sum"); public void init() { // constructs the GUI getContentPane().setLayout(new FlowLayout()); getContentPane().add(textA); getContentPane().add(textB); getContentPane().add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { buttonActionPerformed(evt); } }); } public void buttonActionPerformed(ActionEvent evt) { int numberA = Integer.parseInt(textA.getText()); int numberB = Integer.parseInt(textB.getText()); try { JSObject jsObj = JSObject.getWindow(this); // calls Javascript method and gets return value Object result = jsObj.call("add", new Integer[] {numberA, numberB}); JOptionPane.showMessageDialog(this, "Sum is " + result.toString()); } catch (JSException ex) { ex.printStackTrace(); } } }Compile the applet as follows:
javac -cp JDK_HOME\jre\lib\plugin.jar SimpleApplet.java
NOTE: Replace JDK_HOMEby the real path on your system.Code of the HTML page (TestSimpleApplet.html):<html> <head> <title>Test applet calling Javascript function</title> </head> <body> <center> <applet id="simpleApplet" code="SimpleApplet.class" width="200" height="50" > </applet> </center> </body> <script type="text/javascript"> function add(a, b) { return (a + b); } </script> </html>
3. Passing numeric arguments example
Javascript function:
function multiply(x, y) { return x * y; }
- Passing integer numbers:
Object returnObj = jsObj.call("multiply", new Integer[] {81, 92}); Double result = (Double) returnObj; System.out.println("result is: " + result);
Output: result is 7452.0 - Passing float/double numbers:
Object returnObj = jsObj.call("multiply", new Double[] {81.2, 92.3}); Double result = (Double) returnObj; System.out.println("result is: " + result);
Output: result is 7494.76
4. Passing String arguments example
- Javascript function:
function getFullname(first_name, last_name) { return "Hello " + first_name + " " + last_name; }
- Java code:
String returnValue = (String) jsObj.call("getFullname", new String[] {"Peter", "Smith"}); System.out.println(returnValue);
- Output: Hello Peter Smith
5. Passing boolean arguments example
- Javascript function (set visibility of a div element):
function setTableVisible(visible) { var tableDiv = document.getElementById("tableDiv"); tableDiv.style.visibility = visible ? "visible" : "hidden"; }
- Java code:
jsObj.call("setTableVisible", new Boolean[] {false});
6. Passing array argument example
- Javascript function:
function sumArray(array_numbers) { var total = 0; var i = 0; for (i = 0; i < array_numbers.length; i++) { total += array_numbers[i]; } return total; }
- Java code:
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Object returnObj = jsObj.call("sumArray", new Object[] {numbers}); Double result = (Double) returnObj; System.out.println("result is: " + result);
- Output: result is 55.0
Other Java Applet Tutorials:
- Java Applet Tutorial for beginners
- How to show Java applet in HTML page
- How to sign a Java applet
- How to call Java applet's methods and variables from Javascript
- How to resize Java applet to fit browser's window
- How to submitt HTML form in Java applet
- LiveConnect - The API for communication between Java applet and Javascript
Comments