How to call Delphi code from scripts running in a TWebBrowser (part 1 of 6)

   
Contents, introduction and overview

Contents

Introduction

When writing programs that use the TWebBrowser control as part of the user interface I've sometimes needed to respond to user interaction with the control. The official way to do this is to extend the web browser's external object, and this is the technique we will use in this article.

The external object is part of TWebBrowser's document object model. The object enables interaction with the environment surrounding the browser control – in this case our program.

We can extend the external object by adding methods to it that are implemented in Delphi rather than in JavaScript or VBScript. We do this by creating a COM automation object that exposes the required methods and then notifying the TWebBrowser control that the COM object extends the external object. The new external object methods can then be called from JavaScript or VBScript running in the TWebBrowser. When these methods are called our Delphi code executes.

The rest of this article examines how to use Delphi to create and manipulate the external object.

Overview

The solution divides neatly into three main activities:

  1. Extend the external object in Delphi by creating a COM automation object that exposes the required methods.
  2. Register the extended external object with the browser control so that the object's methods can be called from within the control. We do this by implementing the IDocHostUIHandler interface and enabling the TWebBrowser control to use our implementation.
  3. Call the methods of the extended external object from JavaScript running in the browser control.

The next sections discuss each of the above activities in turn. Finally a case study will be presented that puts the techniques we have learned into practise.

We make a start in the next section by discussing how to extend the external object.