Sample code for 30+ languages & platforms
Java Requires Chilkat v11.4.0+

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a boolean.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Js;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This is the JavaScript function we'll call:

        // function isEven(number) {
        //     return number % 2 === 0;
        // }

        StringBuilder sbScript = new StringBuilder();
        sbScript.append("function isEven(number) { return number % 2 === 0; }");

        Js js = new Js();

        JsonObject result = new JsonObject();
        result.setEmitCompact(false);

        // Call Eval to add the function to the context's global object
        try {
            js.eval(sbScript, result);
        } catch (ChilkatException e) {
            // Examine the result for an exception.
            System.out.println(result.emit());

            // Also examine the LastErrorText.
            System.out.println(e.getLastErrorText());
            return;
        }

        // ------------------------------------------------------------------------------
        // Call the function isEven(8)

        JsonObject funcCall = new JsonObject();

        // Create JSON specifying the function name and arguments

        // {
        //   "name": "isEven",
        //   "args": [ 8 ]
        // }

        funcCall.updateString("name", "isEven");
        funcCall.updateInt("args[0]", 8);

        try {
            js.callFunction(funcCall, result);
        } catch (ChilkatException e) {
            // Examine the result for an exception.
            System.out.println(result.emit());

            // Also examine the LastErrorText.
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(result.emit());

        // Output:
        // {
        //   "type": "bool",
        //   "value": true
        // }

        boolean retval = result.boolOf("value");
        System.out.println(retval);

        // Output:
        // true
    }
}