I am working with a Web API that uses a Javascript interface to make requests, and the response is via a callback Javascript function. Is there a way to call Javascript code from Delphi without using a TWebBrowser
component?
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
Most likely, you'll find your JavaScript editor of choice in Sublime Text, Visual Studio Code, or Brackets. But several other tools—Atom, BBEdit, Notepad++, Emacs, and Vim—all have something to recommend them. Depending on the task at hand, you might find any one of them handy to have around.
You can always run cscript.exe on windows machines.
Advantages:
Disadvantages:
Example program (it's just a proof-of-concept.. there are probably better ways to do this):
program JsExample;
{$APPTYPE CONSOLE}
uses Windows, IoUtils;
// start a new process
function RunProgram(const aProg, aParams: string; aHow2Show: Word; const aWaitTime: dword): boolean;
var LProcInfo: TProcessInformation; LStartUpInfo: TStartupInfo;
begin
FillChar(LStartUpInfo, SizeOf(TStartupInfo), #0); FillChar(LProcInfo, SizeOf(TProcessInformation), #0);
with LStartUpInfo do
begin
cb := SizeOf(LStartUpInfo);
lpReserved := nil; lpDesktop := nil; lpTitle := nil; lpReserved2 := nil; cbReserved2 := 0;
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := aHow2Show;
end;
Result := CreateProcess(nil, PChar(aProg + ' ' + aParams), nil, nil, false, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, LStartUpInfo, LProcInfo);
if Result then
Result := WaitForSingleObject(LProcInfo.hProcess, aWaitTime) <> WAIT_FAILED;
end;
// run javascript code
procedure RunJs(const aJavaScript: String);
var LTmpFileName: String;
begin
LTmpFileName := TPath.ChangeExtension(TPath.GetTempFileName, '.js');
try
TFile.WriteAllText(LTmpFileName, aJavaScript);
RunProgram('cscript', '/NOLOGO "' + LTmpFileName + '"', SW_SHOWNORMAL, INFINITE);
finally
TFile.Delete(LTmpFileName);
end;
end;
// main
begin
// execute some stupid javascript sample code
RunJs
(
'var Text="Hello from JavaScript!";' + // creating a js variable
'for(var i=0;i<Text.length;i++)' + // creating a js looop
' WScript.Echo(Text.charAt(i));' // calling string.charAt() and print some stuff
);
ReadLn;
end.
This method is really simple.. write the JavaScript to a file, then call cscript.exe with the filename as a parameter.
SpiderMonkey
V8
No clue if any of this actually (still) works though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With