Rust Requires Chilkat v11.4.0+
Rust
Call a JavaScript Function Returning an Object
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns an object.Chilkat Rust Downloads
// This is the JavaScript function we'll call:
// function getSettings() {
// return {
// theme: "dark",
// notifications: true,
// version: 1.0
// };
// }
let sb_script = chilkat::StringBuilder::new();
let _ = sb_script.append("function getSettings() {");
let _ = sb_script.append(" return {");
let _ = sb_script.append(" theme: \"dark\",");
let _ = sb_script.append(" notifications: true,");
let _ = sb_script.append(" version: 1.0");
let _ = sb_script.append(" };");
let _ = sb_script.append("}");
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 getSettings()
let func_call = chilkat::JsonObject::new();
// Create JSON specifying the function name and arguments
// The function has no arguments, so we only specify the name.
// {
// "name": "getSettings",
// }
let _ = func_call.update_string("name", "getSettings");
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": "object",
// "value": {
// "theme": "dark",
// "notifications": true,
// "version": 1
// }
// }
// Examine the object's members
println!("theme: {}", result.string_of("value.theme").unwrap_or_default());
println!("notifications: {}", result.bool_of("value.notifications"));
println!("version: {}", result.int_of("value.version"));
// Output:
// theme: dark
// notifications: True
// version: 1