1. Home
  2. Computing & Technology
  3. Delphi Programming

How to locate and highlight a string in a TWebBrowser

By Zarko Gajic, About.com

Here's how to search for a string in a web document (loaded in a TWebBrowser component) and highlight every occurence of it. The WBLocateHighlight locates every occurence of a string passed as a "Text" parameter in a document loaded in a TWebBrowser component passed as the "WB" parameter. The background of the located string is turned to red with the text in white.

~~~~~~~~~~~~~~~~~~~~~~~~~
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;

Usage:
WBLocateHighlight(WebBrowser1,'delphi') ;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to create, use and free TXMLDocument dynamically (without an AV)
« ASP.NET: IsDesignTime

Explore Delphi Programming

More from About.com

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TWebBrowser
  6. How to locate and highlight a string in a TWebBrowser

©2008 About.com, a part of The New York Times Company.

All rights reserved.