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.

7 comments:

[Batch] said...

Can you give a translated example to Delphi?

Thanks!

Roland Beenhakker said...

--Batch
I added a link to a blogpost from Steve Trefethen where you can find Delphi examples

[Batch] said...

Thanks, I appreciate it :)

JavascriptBank.com said...

very cool & good tips, thank you very much for sharing.

Nenaza said...

Have you try something like this?

Dim ArrayObj(2) As Object
ArrayObj (0) = CObj(New String(param1))
ArrayObj (1) = CObj(New String(param2))
WebBrowser1.Document.InvokeScript("test", ObjArr)

It seems you can even catch the returned value ,object or DOM element (MSHTML.dll casting needed) from the invoked function script.

A question:

Is it posible a interaction betwen .NET Windows Forms and a Java Applet with this technique?

Am thuc said...

Thanks so much. It work!

Anonymous said...

Hi..has you tried webkit (with webkitdotnet) or mozilla (moznet)instead IE?..would be cool see a nice explanation like this but using webkit..thanks