Question

I have three functions below to get and set the HTML, the first function captures the HTML DOM, the second function captures the original HTML page, since the last function injects a new code in the TWebBrowser, but does the way I want and need.

After injecting a new code runs successfully, but only visually, when I click with the right button and visualize source code opens the notepad and instead of DOM code I see the code of the page.

Is there any way to rewrite the original HTML?

Get HTML Source Code (DOM).

function GetHTML( WebBrowser : TWebBrowser ) : String;
var
  HTMLElement : IHTMLElement;
begin
  Result := '';
  if Assigned( WebBrowser.Document ) then begin
    HTMLElement := ( WebBrowser.Document as IHTMLDocument2 ).body;
    if Assigned( HTMLElement ) then begin
      while HTMLElement.parentElement <> nil do begin
        HTMLElement := HTMLElement.parentElement;
      end;
      Result := HTMLElement.outerHTML;
    end else begin
      Result := ( WebBrowser.Document as IHTMLDocument2 ).all.toString;
    end;
  end;
end;

Get HTML Source Code ("Original HTML").

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;

Rewrite HTML Source Code (only visually apparent).

procedure WBAppendHTML( WB : SHDocVw.TWebbrowser;const HTML : string );
var
  Doc      : MSHTML.IHTMLDocument2;
  BodyElem : MSHTML.IHTMLBodyElement;
  Range    : MSHTML.IHTMLTxtRange;
begin
  if not SysUtils.Supports( WB.Document, MSHTML.IHTMLDocument2, Doc ) then begin
    Exit;
  end;
  if not SysUtils.Supports( Doc.body, MSHTML.IHTMLBodyElement, BodyElem ) then
  begin
    Exit;
  end;
  Range := BodyElem.createTextRange;
  Range.collapse( False );
  Range.pasteHTML( HTML );
end;
Was it helpful?

Solution

The only way I know of is to download the HTML from the webserver yourself and alter it as needed (which includes inserting a <base href> tag into the <head> so relative links can be resolved), and then load the altered HTML into the TWebBrowser via its IPersisteStreamInit.load() method (if there is no Document loaded yet, navigate the TWebBrowser to the "about:blank" URL first).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top