分享

向WebBrowser中添加静态HTML,执行脚本,载入HTML

 独孤求财 2012-03-20

向WebBrowser中添加静态HTML,执行脚本,载入HTML

时间:2011-5-26来源:yang 作者: peng点击: 227次

*使TWebBrowser中的复制、剪切操作有效:
//把下面4行加到有WebBrowser的单元最后
{ 可能需要引用 ActiveX }
initialization  
  OleInitialize(nil);
finalization
  OleUninitialize;




向WebBrowser中添加静态HTML:
uses MSHTML;

procedure AppendToWB(WB: TWebBrowser; const html: widestring) ;
var
  Range: IHTMLTxtRange;
begin
  Range := ((WB.Document AS IHTMLDocument2).body AS IHTMLBodyElement).createTextRange;
  Range.Collapse(False) ;
  Range.PasteHTML(html) ;
end;

{ 使用:Navigate()完成后,点击Button1 }
procedure TForm1.Button1Click(Sender: TObject) ;
var
  str: string;
begin
  str:= ‘<a href="http://www.">大富翁论坛</a>‘;
  AppendToWB(WebBrowser1, str) ;
end;




执行脚本:
procedure ExecuteScript(doc: IHTMLDocument2; script: string; language: string) ;
begin
  if doc <> nil then
  begin
    if doc.parentWindow <> nil then
      doc.parentWindow.ExecScript(script, Olevariant(language)) ;
  end;
end;
{ 使用:在按钮中加入如下代码 }
var
   script : string;
begin
   WebBrowser1.Navigate(‘about:blank‘);
   script := ‘alert("执行Script脚本成功!");‘;
   ExecuteScript(WebBrowser1.Document as IHTMLDocument2, script, ‘javascript‘)
end;  

 

 

载入脚本

Use ActiveX;

procedure WBLoadHTML(WebBrowser: TWebBrowser; HTMLCode: string) ;
var
   sl: TStringList;
   ms: TMemoryStream;
begin
   WebBrowser.Navigate(‘about:blank‘) ;
   while WebBrowser.ReadyState < READYSTATE_INTERACTIVE do
    Application.ProcessMessages;

   if Assigned(WebBrowser.Document) then
   begin
     sl := TStringList.Create;
     try
       ms := TMemoryStream.Create;
       try
         sl.Text := HTMLCode;
         sl.SaveToStream(ms) ;
         ms.Seek(0, 0) ;
         (WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ;
       finally
         ms.Free;
       end;
     finally
       sl.Free;
     end;
   end;
end;

procedure TForm1.FormCreate(Sender: TObject) ;
var
  sHTML : string;
begin
  sHTML := ‘<a href=http://www./>访问</a>‘ +
           ‘<b>技术文章</b>‘;
  WBLoadHTML(WebBrowser1, sHTML) ;
end;

 高亮网页中的关键字

uses mshtml;

procedure WBLocateHighlight(WB: TWebBrowser; Text: string) ;
const
   prefix = ‘<span style="color:white; background-color: red;">‘;
   suffix = ‘</span>‘;
var
   tr: IHTMLTxtRange;
begin
   if Assigned(WB.Document) then
   begin
     tr := ((wb.Document AS IHTMLDocument2).body AS IHTMLBodyElement).createTextRange;
     while tr.findText(Text, 1, 0) do
     begin
       tr.pasteHTML(prefix + tr.htmlText + suffix) ;
       tr.scrollIntoView(True) ;
     end;
   end;
end;

{ 使用方法 }
WBLocateHighlight(WebBrowser1, ‘delphi‘) ;

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多