1. Computing

How to locate and highlight a string in a TWebBrowser

From , former About.com Guide

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

©2013 About.com. All rights reserved.