WPF - call javascript function present on html page from web browser

I am new to wpf. I use "WebBroswer" in my wpf application to display a Google map. I have a googlemap.htm page and it contains a JavaScript function with initialization (lat, log). Now I want to call this function from my .xaml.cs file with lat and log parameters. Can someone help me.

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> 
+2
source share
1 answer

The easiest way is to use the WebBrowser.InvokeScript method:

  this.WebBrowser.InvokeScript("initialize", 1, 2); 

Alternatively, you can also rewrite JavaScript code as follows:

  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 can also call myfunc without the 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}); } 
+5
source

Source: https://habr.com/ru/post/1267190/


All Articles