Calling Javascript in a web page from Delphi

by Jan Verhoeven, 9 August 2002

When working on version 10 of my BackEdit program, I needed the possibility to call a javascript function from Delphi. In BackEdit I use the Internet Explorer WebBrowser as an embedded control. When an HTML page is loaded in the webbrowser I wanted to invoke functions in that page from Delphi code.

The solution that I found is simple and can be extended as needed:

procedure TBackEditF.jscript1Click(Sender: TObject);
var
  doc:IHTMLdocument2;
  elem:IHTMLElement;
begin
  try
    doc:=sidebar.document as IHTMLdocument2;
    elem:=doc.all.item('gateway',0) as IHTMLElement;
    elem.click;
  except
  end;
end;

The HTML document itself could be something like: 
<html><head><title>Delphi - Javascript connection</title>
<script language='javascript'>
  function myrouter() {
    cmd=external.command
external.command=''
  }
</script>
</head>
<body>
<input type='hidden' id='gateway'  onclick='myrouter()'>

</body></html>

By clicking the hidden form field from Delphi the function myfunction is invoked. In the javascript function I can call the external object which invokes the ongetexternal event of the webbrowser (I am using the TEmbeddedWB wrapper component which makes this event available). From the external object (which returns BackEdit's automation interface) the javascript function can learn what is expected and respond accordingly, dispathching to other functions as needed.