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

How to Execute a JavaScript Code on a TWebBrowser Document

By Zarko Gajic, About.com

The TWebBrowser Delphi control provides access to the Web browser functionality from your Delphi applications.

Here's how to execute a custom script (JavaScript or VBScript) function on a HTML document loaded in the TWebBrowser control:

uses MSHTML_TLB, SHDocVw;

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;
Usage (in some Button OnClick event handler, for example):
var
   script : string;
begin
   //locate the first element with ID attribute = "main" and show its tag

   script := 'var elemMain = document.getElementById("main") ; if (elemMain != null) { alert(elemMain.tagName) ; }';

   ExecuteScript(EmbeddedWB1.Document as IHTMLDocument2, script, 'javascript')
end;
Note: More TWebBrowser Tips'n'Tricks!

Delphi tips navigator:
» How to Browse Delphi's VCL Source Code
« Add Console Input and Output for a GUI Delphi Application

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TWebBrowser
  6. How to Execute a JavaScript Code on a TWebBrowser Document

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

All rights reserved.