Calling JavaScript

You can simply call JavaScript from C# but actually, C# is used to implement the server-side application whereas, JavaScript is used to implement the client-side application but it isn’t always. You can embed the local web page file to the C# application via WebBrowser Component. So, It should be able to call JavaScript via C#.

How to

1. Put the WebBrowser component into the application’s form.
*The WebBrowser compoenet is a default component. So, you just simply drag from the toolbox to the application’s form.

2. Use Navigate method to load the web page.

  1. webBrowser1.Navigate(@"C:\Users\Thada\documents\visual studio 2010\Projects\GoogleMapApi\GoogleMapApi\googlemap.html");

Suppose: webBrowser1 is the WebBrowser’s object.

3. Call InvokeScript method from the HtmlDocument object which can be accessed by WebBrowser’s attribute.

Get HtmlDocument
  1. HtmlDocument doc = webBrowser1.Document;

InvokeScript Method
  1. object InvokeScript(string scriptName, object[] args)

JavaScript
  1. <script type="text/javascript" language="JavaScript">
  2.     function initialize() {
  3.         var latlng = new google.maps.LatLng(-34.397, 150.644);
  4.         var myOptions = {
  5.             zoom: 8,
  6.             center: latlng,
  7.             mapTypeId: google.maps.MapTypeId.ROADMAP
  8.         };
  9.         var map = new google.maps.Map(document.getElementById("map_canvas"),
  10.     myOptions);
  11.     }
  12.  
  13.     function msgbox(text) {
  14.         alert(text);
  15.     }
  16.  
  17.     function getint() {
  18.         return 1.23;
  19.     }
  20.  
  21. </script>

C#
  1. doc.InvokeScript("initialize", null); //no argument

C#
  1. doc.InvokeScript("msgbox", new object[] { "To You" }); //With one argument

Note: Sometimes, you need some value return from calling JavaScript. The InvokeScript also returns object out but you have to know know what exact type of the object from JavaScript first (JavaScript is dynamic.) by using GetType method of the object to know the type is and then convert the object to that type.

  1. object a = doc.InvokeScript("getint", null);
  2. Console.WriteLine(a.GetType()); // print System.Int32
  3. //rewrite
  4. int a = (Int32)doc.InvokeScript("getint", null);