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

Call a JavaScript Function Returning a String

See more JavaScript Examples

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

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 greet(name) {
        //     return "Hello, " + name + "!";
        // }

        StringBuilder sbScript = new StringBuilder();
        sbScript.append("function greet(name) { return \"Hello, \" + name + \"!\"; }");

        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 greet("Michael")

        JsonObject funcCall = new JsonObject();

        // Create JSON specifying the function name and arguments

        // {
        //   "name": "greet",
        //   "args": [ "Michael" ]
        // }

        funcCall.updateString("name", "greet");
        funcCall.updateString("args[0]", "Michael");

        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": "string",
        //   "value": "Hello, Michael!"
        // }

        String retval = result.stringOf("value");
        System.out.println(retval);

        // Output:
        // Hello, Michael!
    }
}