3

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>

1 Answer 1

7

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});
}
Sign up to request clarification or add additional context in comments.

6 Comments

I am using vs 2008. The dynamic key is not support. Any help.
I am getting this error Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME)). Please help me.
Make sure that your page loaded correctly without any Internet Explorer warnings. When I tested this code, there was a warning about ActiveX content or something like that.
Thank you very munch for you post. I have changed my code and still getting error. I have posted my complete code in the below link:- stackoverflow.com/questions/14502898/… Can you help me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.