Search code examples
delphidelphi-7twebbrowser

How can I get HTML source code from TWebBrowser


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.


Solution

  • 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;