Delphi 通过WebBrowser 调用JS时,为防止版本问题导致调用失败,需要在html中增加
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
- 示例
html 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title></title>
<script>
function f1(s){ //定义一个简单的方法f1(),传入参数为字符串 s ,返回结果如下
return "Hello Test "+s;
}
</script>
</head>
<body>
<div>
<button onclick="f1('tt')"> 测试1</button>
</div>
</body>
</html>
- Delphi 调用
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw, StdCtrls;
type
TForm1 = class(TForm)
WebBrowser1: TWebBrowser;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
WebBrowser1.Navigate('http://127.0.0.1:8848/site/t1.html');
end;
procedure TForm1.Button2Click(Sender: TObject);
var
s:string;
begin
s:=WebBrowser1.OleObject.document.parentWindow.f1('张三'); //调用javascript 方法,传入参数并返回值
caption:=s; //返回结果 Hello Test 张三
end;
procedure TForm1.Button3Click(Sender: TObject);
var
s:string;
begin
s:=WebBrowser1.OleObject.document.parentWindow.execScript('f1(''李四'')','JavaScript'); //执行一段javascript脚本,此时不能处理返回值
Caption:=s; //返回 空
end;
procedure TForm1.Button4Click(Sender: TObject);
var
s:string;
begin
s:=WebBrowser1.OleObject.document.Script.eval('f1(''李四'')'); //执行JavaScript中的eval,通过eval 方法解释执行JavaScript方法f1(),传入参数并返回数据
Caption:=s; //返回结果 Hello Test 李四
end;
end.
标签:f1,end,Sender,Delphi,TForm1,TObject,JS,WebBrowser,procedure
From: https://www.cnblogs.com/sundh1981/p/17523057.html