Sample code for 30+ languages & platforms
Rust 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 Rust Downloads

Rust

// This is the JavaScript function we'll call:

// function greet(name) {
//     return "Hello, " + name + "!";
// }

let sb_script = chilkat::StringBuilder::new();
let _ = sb_script.append("function greet(name) { return \"Hello, \" + name + \"!\"; }");

let js = chilkat::Js::new();

let result = chilkat::JsonObject::new();
result.set_emit_compact(false);

// Call Eval to add the function to the context's global object
if js.eval(&sb_script, &result).is_err() {
    // Examine the result for an exception.
    println!("{}", result.emit().unwrap_or_default());

    // Also examine the LastErrorText.
    println!("{}", js.last_error_text());
    return;
}

// ------------------------------------------------------------------------------
// Call the function greet("Michael")

let func_call = chilkat::JsonObject::new();

// Create JSON specifying the function name and arguments

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

let _ = func_call.update_string("name", "greet");
let _ = func_call.update_string("args[0]", "Michael");

if js.call_function(&func_call, &result).is_err() {
    // Examine the result for an exception.
    println!("{}", result.emit().unwrap_or_default());

    // Also examine the LastErrorText.
    println!("{}", js.last_error_text());
    return;
}

println!("{}", result.emit().unwrap_or_default());

// Output:
// {
//   "type": "string",
//   "value": "Hello, Michael!"
// }

let retval = result.string_of("value").unwrap_or_default();
println!("{}", retval);

// Output:
// Hello, Michael!