How to click Button Class WebBrowser Delphi

Fake picture Fake · Oct 16, 2014 · Viewed 8.4k times · Source

How to click in this button in TWebBrowser on Delphi

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

Answer

stanleyxu2005 picture stanleyxu2005 · Oct 16, 2014

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;