0

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;

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.