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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This is the JavaScript function we'll call:

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

  final sbScript = CkStringBuilder();
  sbScript.append('function greet(name) { return "Hello, " + name + "!"; }');

  final js = CkJs();

  final result = CkJsonObject();
  result.emitCompact = false;

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

    // Also examine the LastErrorText.
    print(e.lastErrorText);
    return;
  }

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

  final funcCall = CkJsonObject();

  // 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);
  } on ChilkatException catch (e) {
    // Examine the result for an exception.
    print(result.emit());

    // Also examine the LastErrorText.
    print(e.lastErrorText);
    return;
  }

  print(result.emit());

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

  final retval = result.stringOf('value');
  print(retval);

  // Output:
  // Hello, Michael!
}