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

Delphi ActiveX
var
success: Integer;
sbScript: TChilkatStringBuilder;
js: TChilkatJs;
result: TChilkatJsonObject;
funcCall: TChilkatJsonObject;
retval: WideString;

begin
success := 0;

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

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

sbScript := TChilkatStringBuilder.Create(Self);
sbScript.Append('function greet(name) { return "Hello, " + name + "!"; }');

js := TChilkatJs.Create(Self);

result := TChilkatJsonObject.Create(Self);
result.EmitCompact := 0;

//  Call Eval to add the function to the context's global object
success := js.Eval(sbScript.ControlInterface,result.ControlInterface);
if (success = 0) then
  begin
    //  Examine the result for an exception.
    Memo1.Lines.Add(result.Emit());

    //  Also examine the LastErrorText.
    Memo1.Lines.Add(js.LastErrorText);
    Exit;
  end;

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

funcCall := TChilkatJsonObject.Create(Self);

//  Create JSON specifying the function name and arguments

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

funcCall.UpdateString('name','greet');
funcCall.UpdateString('args[0]','Michael');

success := js.CallFunction(funcCall.ControlInterface,result.ControlInterface);
if (success = 0) then
  begin
    //  Examine the result for an exception.
    Memo1.Lines.Add(result.Emit());

    //  Also examine the LastErrorText.
    Memo1.Lines.Add(js.LastErrorText);
    Exit;
  end;

Memo1.Lines.Add(result.Emit());

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

retval := result.StringOf('value');
Memo1.Lines.Add(retval);

//  Output:
//  Hello, Michael!