有时做项目难免用到代码交叉调用,delphi中执行js就是一种,两种方法可用:
一、使用webbrower,比较麻烦
二、使用ScriptControl,简单方便:
1.首先
uses ComObj;
2.通用函数:
function ExecScript(Code,Lang,Func:string):string;
var
script:OleVariant;
begin
try
script:=CreateOleObject('ScriptControl');
script.Language:=Lang;
script.AddCode(Code);
Result:=script.Eval(Func);
except
end;
end;
3.放入一个memo,直接在form的create时,loadfromfile即可,或是直接把javascript代码放到memo中
procedure TForm1.FormCreate(Sender: TObject);
begin
mmoscript.Lines.LoadFromFile('uifordata.js');
end;
4.调用
cbbValue7.Text := ExecScript(mmoscript.Text,'JavaScript','function1(123)');
注意:本方法调用时,javascript的全局变量像screen不可用,会提示未定义。
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Edit1: TEdit; Label1: TLabel; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} uses ComObj; {此函数需要 ComObj 单元的支持} {参数 JsCode 是要执行的 Js 代码; 参数 JsVar 是要返回的变量} function RunJs(const JsCode, JsVar: string): string; var script: OleVariant; begin try script := CreateOleObject('ScriptControl'); script.Language := 'JavaScript'; script.ExecuteStatement(JsCode); Result := script.Eval(JsVar); except Result := ''; end; end; procedure TForm1.Button1Click(Sender: TObject); var s: string; begin s := RunJs(Memo1.Text, 'str'); ShowMessage(s); end; end.