카테고리 없음

[COM/OLE] TWebBrowser에서 JavaScript 호출하기

쇼핑스크래퍼3 2023. 8. 29. 08:16

<!----------------------- 예제 test.html  ------------------------>
<html><head><title>Delphi - Javascript connection</title>
<script language='JavaScript'>
  function showalert() {
    alert('Hello JavaScript');
  }
</script>
</head>
<body>
<input type='hidden' id='myJavaScript' onclick='showalert()'>
김영대 http://www.howto.pe.kr
</body></html>


//------------------------ 델파이 예제 소스 -------------------------
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, OleCtrls, SHDocVw, StdCtrls, MSHTML_TLB;

type
  TForm1 = class(TForm)
    WebBrowser1: TWebBrowser;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  WebBrowser1.Navigate('test.html', EmptyParam, EmptyParam, EmptyParam, EmptyParam);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  doc: IHTMLdocument2;
  elem: IHTMLElement;
begin
  try
    doc  := WebBrowser1.document as IHTMLdocument2;
    // 개체의 id 속성을 기반으로 호출한다
    elem := doc.all.item('myJavaScript',0) as IHTMLElement;
    elem.click;
  except
  end;
end;

end.