【问题标题】:It is possible rewrite the Document property and reinject the HTML of a page by TWebBrowser?是否可以通过 TWebBrowser 重写 Document 属性并重新注入页面的 HTML?
【发布时间】:2014-01-14 20:33:38
【问题描述】:

我在下面有三个函数来获取和设置 HTML,第一个函数捕获 HTML DOM,第二个函数捕获原始 HTML 页面,因为最后一个函数在 TWebBrowser 中注入了新代码,但是按照我想要的方式和需要。

注入新代码成功运行后,但仅在视觉上运行,当我单击右键并可视化源代码时,会打开记事本,而不是 DOM 代码,我看到的是页面代码。

有没有办法重写原来的 HTML?

获取 HTML 源代码 (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;

获取 HTML 源代码(“原始 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;

重写 HTML 源代码(仅在视觉上明显)。

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;

【问题讨论】:

    标签: delphi delphi-xe2 delphi-xe twebbrowser


    【解决方案1】:

    我知道的唯一方法是自己从网络服务器下载 HTML 并根据需要进行更改(包括在 &lt;head&gt; 中插入 &lt;base href> 标签,以便解析相关链接),然后加载通过其IPersisteStreamInit.load() 方法将HTML 更改为TWebBrowser(如果尚未加载Document,请先将TWebBrowser 导航到"about:blank" URL)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多