React Native Requires Chilkat v11.4.0+
React Native
Call a JavaScript Function Returning a String
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns a string.Chilkat React Native Downloads
import { Js, JsonObject, StringBuilder } from '@chilkat/react-native'
async function chilkatExample() {
// This is the JavaScript function we'll call:
// function greet(name) {
// return "Hello, " + name + "!";
// }
const sbScript = new StringBuilder();
sbScript.append('function greet(name) { return "Hello, " + name + "!"; }');
const js = new Js();
const result = new JsonObject();
result.emitCompact = false;
// Call Eval to add the function to the context's global object
try {
await js.evalAsync(sbScript, result);
} catch {
// Examine the result for an exception.
console.log(result.emit());
// Also examine the LastErrorText.
console.log(js.lastErrorText);
return;
}
// ------------------------------------------------------------------------------
// Call the function greet("Michael")
const 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 {
await js.callFunctionAsync(funcCall, result);
} catch {
// Examine the result for an exception.
console.log(result.emit());
// Also examine the LastErrorText.
console.log(js.lastErrorText);
return;
}
console.log(result.emit());
// Output:
// {
// "type": "string",
// "value": "Hello, Michael!"
// }
const retval = result.stringOf('value');
console.log(retval);
// Output:
// Hello, Michael!
}