Kyle Williamson
Kyle Williamson

Reputation: 2184

How to scroll to the bottom of a TWebBrowser document in Delphi

I'm trying to scroll to the bottom of my displayed TWebBrowser document programmatically.

I've tried using the scroll method:

uses
  MSHTML;

procedure TForm1.Button1Click(Sender: TObject);
var
  Document: IHTMLDocument2;
begin
  Document := WebBrowser.Document as IHTMLDocument2;
  Document.parentWindow.scroll(0, Document.body.offsetHeight);
end;

I also tried using ScrollIntoView(false);:

procedure TForm1.Button1Click(Sender: TObject);
var
  Document: IHTMLDocument2;
begin
  Document := WebBrowser.Document as IHTMLDocument2;
  Document.Body.ScrollIntoView(false);
end;

Upvotes: 0

Views: 536

Answers (1)

Marcodor
Marcodor

Reputation: 5751

Just run JavaScript code to scroll it:

const
  jsScrollDown = 'window.scrollTo(0, document.body.scrollHeight);';
var
  Doc: IHTMLDocument2;
  Hwn: IHTMLWindow2;
begin
  Doc := WebBrowser1.Document as IHTMLDocument2;
  if not Assigned(Doc) then Exit;
  Hwn := Doc.parentWindow;
  Hwn.execScript(jsScrollDown, 'JavaScript');

Or next generation, TEdgeBrowser supports directly scripts execution:

EdgeBrowser1.ExecuteScript(jsScrollDown);

Running JS code, allows scrolling easily to any element of the HTML document.

Using MS interfaces, without JS, it could be done like:

var
  Doc: IHTMLDocument2;
  Hwn: IHTMLWindow2;
begin
  Doc := WebBrowser1.Document as IHTMLDocument2;
  if not Assigned(Doc) then Exit;
  Hwn := Doc.parentWindow;
  Hwn.scrollTo(0, (Doc.body as IHTMLElement2).scrollHeight);

Be aware, MS interfaces works in legacy IE mode only, not supported by Edge engine.

Upvotes: 2

Related Questions