How can I get HTML source code from TWebBrowser

Someone picture Someone · Apr 10, 2012 · Viewed 26.3k times · Source

How can I get source code from WebBrowser component?

I want to get source code of active page on WebBrowser component and write it to a Memo component.

Thanks.

Answer

RRUZ picture RRUZ · Apr 10, 2012

You can use the IPersistStreamInit Interface and the save method to store the content of the Webbrowser in a Stream.

Uses 
  ActiveX;

function GetWebBrowserHTML(const WebBrowser: TWebBrowser): String;
var
  LStream: TStringStream;
  Stream : IStream;
  LPersistStreamInit : IPersistStreamInit;
begin
  if not Assigned(WebBrowser.Document) then exit;
  LStream := TStringStream.Create('');
  try
    LPersistStreamInit := WebBrowser.Document as IPersistStreamInit;
    Stream := TStreamAdapter.Create(LStream,soReference);
    LPersistStreamInit.Save(Stream,true);
    result := LStream.DataString;
  finally
    LStream.Free();
  end;
end;