delphi xe 10.2 调用跟HTML交互

时间:2024-05-24 07:32:24

学习了下网上一些文档自己打代码试了下,现在贴出代码以及说明供大家参考

1.HTML代码如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <title>Test
</title>
  </head>

  <body>
  输入内容:<input id="P1">
  <span id="msg" style="DISPLAY: none" οnclick="alert(this.innerText)"></span>
</body>
</html>

2、界面

delphi xe 10.2 调用跟HTML交互

3、后台代码 记得引用 MSHTML单元

implementation
uses MSHTML;

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
  Doc:IHTMLDocument2;
  Ele :IHTMLElement;
begin
  if wb1.Document<>nil then
  begin
  //T1是Input 的 Id 值
     Doc:=IHTMLDocument2(wb1.Document);
     Ele :=Doc.all.item('msg',0)as IHTMLElement;
     if Ele<>nil then
     begin
       Ele.innerText:='我是delphi给HTML赋值消息';
       ELe.click;
     end;
  end;

end;

procedure TForm1.btn2Click(Sender: TObject);
var
  Doc:IHTMLDocument2;
  inputtext :IHTMLInputElement;
begin
  //P1是Input 的 Id 值
  if wb1.Document<>nil then
  begin
    Doc:=IHTMLDocument2(wb1.Document);
    inputtext :=Doc.all.item('P1',0)as IHTMLInputElement;
    inputtext.value :=edt1.Text;
  end;

end;

procedure TForm1.btn3Click(Sender: TObject);
var
  Doc:IHTMLDocument2;
  inputtext :IHTMLInputElement;
begin
  if wb1.Document<>nil then
  begin
  //P1是Input 的 Id 值
     Doc:=IHTMLDocument2(wb1.Document);
     inputtext :=Doc.all.item('P1',0)as IHTMLInputElement;
     edt2.Text :=inputtext.value;
  end;

end;

procedure TForm1.FormShow(Sender: TObject);
begin
  wb1.Navigate('E:\Delphi\调用Web-js\alert.html');
end;