Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Call a JavaScript Function Returning a String

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a string.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Js,
  Chilkat.StringBuilder,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  sbScript: TStringBuilder;
  js: TJs;
  result: TJsonObject;
  funcCall: TJsonObject;
  retval: string;

begin
  success := False;

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

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

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

  js := TJs.Create;

  result := TJsonObject.Create;
  result.EmitCompact := False;

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

      //  Also examine the LastErrorText.
      WriteLn(js.LastErrorText);
      Exit;
    end;

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

  funcCall := TJsonObject.Create;

  //  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,result);
  if (success = False) then
    begin
      //  Examine the result for an exception.
      WriteLn(result.Emit());

      //  Also examine the LastErrorText.
      WriteLn(js.LastErrorText);
      Exit;
    end;

  WriteLn(result.Emit());

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

  retval := result.StringOf('value');
  WriteLn(retval);

  //  Output:
  //  Hello, Michael!


  sbScript.Free;
  js.Free;
  result.Free;
  funcCall.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.