我使用此例程将HTML添加到TWebbrowser文档中:
procedure WBAppendHTML(WB: SHDocVw.TWebbrowser; const HTML: string);
(*Appends the given HTML to the end of the given web browser control's current document body.
Does nothing if no document is loaded, if the document does not support the DOM, or if the document is a frameset.*)
var
Doc: MSHTML.IHTMLDocument2;
BodyElem: MSHTML.IHTMLBodyElement;
Range: MSHTML.IHTMLTxtRange;
begin
if not System.SysUtils.Supports(WB.Document, MSHTML.IHTMLDocument2, Doc) then
EXIT;
if not System.SysUtils.Supports(Doc.body, MSHTML.IHTMLBodyElement, BodyElem) then
EXIT;
Range := BodyElem.createTextRange;
Range.collapse(False);
Range.pasteHTML(HTML);
end;
当HTML如下所示时,这是有效的:'我的文字':
WBAppendHTML(wb, '<B>My text</B>');
但它不适用于HTML评论:
WBAppendHTML(wb, '<!-- {93706302-FC6C-43D6-8362-DE71550AD998} -->');
为什么这不起作用? 那么如何在TWebbrowser文档中添加HTML注释呢?
编辑201306142055:
为了更好地理解我如何测试是否添加了评论:在尝试使用WBAppendHTML附加评论后,我将文档复制到剪贴板:
// select the entire document:
wb.ExecWB(OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT);
// copy the text to Clipboard:
wb.ExecWB(OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT);
// clear the selection:
wb.ExecWB(OLECMDID_CLEARSELECTION, OLECMDEXECOPT_DONTPROMPTUSER);
之后,我从剪贴板内容的CF_HTML部分检索HTML源:
function GetClipboardAsHTMLSource: string;
var
Data: THandle;
Ptr: PAnsiChar; // PChar;
begin
Result := '';
Clipboard.Open;
try
Data := Clipboard.GetAsHandle(CF_HTML);
if Data <> 0 then
begin
Ptr := PAnsiChar(GlobalLock(Data));
if Ptr <> nil then
begin
try
Result := UTF8Decode(Ptr);
finally
GlobalUnlock(Data);
end;
end;
end;
finally
Clipboard.Close;
end;
end;