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

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

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

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: Boolean;

begin
  success := False;

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

  //  function isEven(number) {
  //      return number % 2 === 0;
  //  }

  sbScript := TStringBuilder.Create;
  sbScript.Append('function isEven(number) { return number % 2 === 0; }');

  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 isEven(8)

  funcCall := TJsonObject.Create;

  //  Create JSON specifying the function name and arguments

  //  {
  //    "name": "isEven",
  //    "args": [ 8 ]
  //  }

  funcCall.UpdateString('name','isEven');
  funcCall.UpdateInt('args[0]',8);

  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": "bool",
  //    "value": true
  //  }

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

  //  Output:
  //  True


  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.