我正在使用一个使用
Javascript接口发出请求的Web API,响应是通过回调Javascript函数.有没有办法从Delphi调用Javascript代码,而不使用TWebBrowser组件?
解决方法
您可以随时在Windows机器上运行cscript.exe.
优点:
>自Windows 98以来,它可用于所有默认的Windows安装.
这是死的容易.
>不需要第三方Delphi组件.
>不需要dll的包装器,所以部署很简单.
缺点:
>你会产生新的流程.在网络服务器上启动cscript.exe感觉错误.我不知道安全性是什么.
>您无法直接访问脚本引擎的内部.
示例程序(这只是一个概念证明…可能有更好的方法来做到这一点):
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,false,CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,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.