Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Call a JavaScript Function Returning an Object
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns an object.Chilkat Pascal (Lazarus/Delphi) Downloads
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;
begin
success := False;
// This is the JavaScript function we'll call:
// function getSettings() {
// return {
// theme: "dark",
// notifications: true,
// version: 1.0
// };
// }
sbScript := TStringBuilder.Create;
sbScript.Append('function getSettings() {');
sbScript.Append(' return {');
sbScript.Append(' theme: "dark",');
sbScript.Append(' notifications: true,');
sbScript.Append(' version: 1.0');
sbScript.Append(' };');
sbScript.Append('}');
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 getSettings()
funcCall := TJsonObject.Create;
// Create JSON specifying the function name and arguments
// The function has no arguments, so we only specify the name.
// {
// "name": "getSettings",
// }
funcCall.UpdateString('name','getSettings');
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": "object",
// "value": {
// "theme": "dark",
// "notifications": true,
// "version": 1
// }
// }
// Examine the object's members
WriteLn('theme: ' + result.StringOf('value.theme'));
WriteLn('notifications: ' + result.BoolOf('value.notifications'));
WriteLn('version: ' + result.IntOf('value.version'));
// Output:
// theme: dark
// notifications: True
// version: 1
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.