I am new to WPF. I am using "WebBroswer" in my wpf application to render a Google map. I have a googlemap.htm page and it contains a initialize(lat, log) JavaScript function. Now I want to call this function from my .xaml.cs file with lat and log parameters.
Googlemap.htm
<script>
function initialize(lat, log) {
var mapProp = {
center: new google.maps.LatLng(lat, log),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The easiest approach is to use WebBrowser.InvokeScript
method:
this.WebBrowser.InvokeScript("initialize", 1, 2);
Alternatively you could also rewrite you JavaScript code like this:
function initialize(lat, log) {
var mapProp = {
center: new google.maps.LatLng(lat, log),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
document.myfunc = initialize; // expose it to the document scope
google.maps.event.addDomListener(window, 'load', initialize);
So now you can access myfunc
from C# code:
private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
dynamic document = WebBrowser.Document;
document.myfunc(1, 2);
}
You could also invoke myfunc
without dynamic
keyword:
private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
var document = this.WebBrowser.Document;
document.GetType().InvokeMember("myfunc", BindingFlags.InvokeMethod, null, document, new object[] {1, 2});
}