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

How to Enumerate Web Browser Windows and Retrieve Document Info (Url, Htm, Node)

By Zarko Gajic, About.com

Code submitted by Denis Kirin

Here's a sample Delphi project to get the list of all opened Web Browser instances. Use the code to learn how to extract the URL, document HTML, document text and all the tags with their attributes.

Enumerating WebBrowser Windows

To get the list of all active (opened) Web Browser windows, we need to instantiate the TShellWindows class found in the "shDocvw.pas" unit. An item in the list is an IDispatch value. If the item is IWebBrowser2 - the window is a Web Browser window.

In Delphi code "words":

procedure TForm1.GetBrowsersButtonClick(Sender: TObject) ;
var
   ShellWindows: TShellWindows;
   ShellWindowDisp: IDispatch;
   WebBrowser: IWebbrowser2;
   Count: integer;
begin
   BrowserList.Clear;
   ShellWindows := TShellWindows.Create(nil) ;
   try
     for Count := 0 to ShellWindows.Count - 1 do
     begin
       ShellWindowDisp := ShellWindows.Item(Count) ;
       if ShellWindowDisp = nil then Continue;
       ShellWindowDisp.QueryInterface(iWebBrowser2, WebBrowser) ;
       if WebBrowser.LocationURL = '' then Continue;
       if Assigned(WebBrowser.Document) then
         BrowserList.Items.Add(WebBrowser.LocationURL) ;
     end;
   finally
     ShellWindows.Free;
   end;
end;
The code above fills a TListBox named "BrowserList" with the URLs of the found Web Browser instances.

WebBrowser Info

For a selected web browser document, we can simply extract the HTML, document's text and all the tags:
...
   Document := WebBrowser.Document;
...
   DocTextMemo.Lines.Text := Document.Body.innerText;
   DocHtmlMemo.Lines.Text := Document.Body.innerHTML;

   for ElementCount := 0 to Document.All.length - 1 do
   begin
     DocElement := Document.All.Item(ElementCount) ;
     ElementNode := NodeTree.Items.Add(nil, DocElement.TagName) ;
     if DocElement.innerHTML <> '' then NodeTree.Items.AddChild(NodeTree.Items.AddChild(ElementNode, 'HTML'), DocElement.innerHTML) ;

     if DocElement.innerText <> '' then NodeTree.Items.AddChild(NodeTree.Items.AddChild(ElementNode, 'Text'), DocElement.innerText) ;
   end;
Download Web Browser Enumerator

Explore Delphi Programming

More from About.com

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Internet / Network
  5. How to Enumerate Web Browser Windows and Retrieve Document Info (Url, Htm, Node) using Delphi

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

All rights reserved.