Tuesday, March 09, 2010

Two way interaction with JavaScript in Winforms using Webbrowser

In a recent project I had to integrate Google maps into a Winforms application. To use Google Maps from a desktop client you must be able to call the Javascript in webpage, which can be done with the Webbrowser component.

Calling JavaScript from C#
Calling JavaScript in a Webbrowser component is very easy. JavaScript is exposed through the IHTMLWindow2 interface which can be referenced from the IHTMLDocument2 interface through the parentWindow property.

doc = webBrowser1.Document.
DomDocument as IHTMLDocument2;
doc.parentWindow.execScript("createMapMarker
("52.3738007, 4.8909347", 1);", "JavaScript");

Calling C# from JavaScript
Calling C# code from JavaScript can be done using the ObjectForScripting property of the Webbrowser component. The object can be called in JavaScript using window.external. The communication is established through COM interop so the class should be visible for COM.
//Class example
[ComVisible(true)]
public class ExternalApplication
{
public string GetApplicationName()
{
return "The application";
}
}
//Connect it to the webbrowser
webbrowser1.ObjectForScripting
= new ExternalApplication();

From JavaScript call the external application, our C# app, like this:

(Google maps click event example)
function createMapMarker(lat, lng, html) {
var point = new GLatLng(parseFloat(lat),parseFloat(lng));
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
var appname = window.external.GetApplicationName();
alert(appname);
});
map.addOverlay(marker);
return marker;
}

For Delphi equivalent code take a look at Steve Trefethen blog serie about Google Maps / Delphi integration here.