【发布时间】: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