How to click Button Class WebBrowser Delphi

2019-07-29 14:41发布

问题:

How to click in this button in TWebBrowser on Delphi

<button class="btn btn-primary btn-block" type="button" onclick="login()">Sign in</button>

回答1:

I do not have a Delphi compiler right now. The code is written using brain compiler. But it should work in general.

Use OleObject

You can use oleobject interface to access the DOM.

var
  Buttons: OleVariant;
  Button: OleVariant;
  I: Integer;
begin
  Buttons := WebBrowser1.OleObject.Document.getElementsByTagName("button");
  for I := 0 to Buttons.Length - 1 do
  begin
    Button := Buttons.item(I);
    if Button.innerText = 'Sign in' then
    begin
      Button.click();
      Break;
    end;
  end;
end;

Run External Script

Another approach is to call execScript interface. The benefit is that you can load a chunk of javascript code from external source, instead of compiling the whole project.

uses
  MSHTML_TLB, SHDocVw;

procedure ExecuteScript;
var
  Script: string;
  DocPtr: IHTMLDocument2;
  WinPtr: IHTMLWindow3;
begin
  Script := 'your_javascript_code'; // Alternatively read from file

  if Supports(WebBrowser1.Document, IHTMLDocument2, DocPtr) and
     Supports(DocPtr.parentWindow, IHTMLWindow3, WinPtr) then
    WinPtr.execScript(Script, 'javascript');
end;