DotNetCurry Logo

How to Invoke and Pass values to a Javascript function from a WebBrowser component using Windows Forms

Posted by: Suprotim Agarwal , on 8/28/2008, in Category WinForms & WinRT
Views: 87161
Abstract: This is a short article describing how you can invoke and pass values to a javascript function from a WebBrowser component using Windows Forms. In this article, we will navigate to a HTML page using the WebBrowser component and pass values to the javascript function kept inside the page, using Windows Forms
How to Invoke and Pass values to a Javascript function from a WebBrowser component using Windows Forms
 
This is a short article describing how you can invoke and pass values to a javascript function from a WebBrowser component using Windows Forms. In this article, we will navigate to a HTML page using the WebBrowser component and pass values to the javascript function kept inside the page, using Windows Forms. Let us see the steps required to do so:
Step 1: Open Visual Studio > File > New > Project. In the Project Types pane, choose the language of your choice (Visual C# or Visual Basic). In the Templates pane, choose Windows Application. Choose a name and location for the project and click OK.
Step 2: Drag and drop a button(btnBrowse) and a WebBrowser(webBrowser1) component to the form. Set the ‘Dock’ property of the WebBrowser component to ‘Bottom’.
Step 3: Now create a HTML page that will contain the javascript function. I have created this page on my D:\ and named it TestPage.html. The html after adding the javascript function will look similar to the following:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
      <head>
            <title>Calling javascript</title>
            <script type="text/javascript" language="javascript">
            function DisplayName(name)
            {
                 this.lbl1.document.writeln("Welcome " + name);
            }
         </script>
      </head>
      <body>
      <div>
      <label id="lbl1"></label>
      </div>
      </body>
</html>
We will be calling the function ‘DisplayName’ and pass a value to this function from our WebBrowser component.
Step 4: Create an event handler for the WebBrowser_DocumentCompleted event. We will be calling the javascript using the Document.InvokeScript method. This method executes a scripting function defined in an html page.
C#
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (e.Url.Equals(webBrowser1.Url))
        webBrowser1.Document.InvokeScript("DisplayName", new object[] {"dotnetcurry"});
}
VB.NET
Private Sub webBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
      If e.Url.Equals(webBrowser1.Url) Then
            webBrowser1.Document.InvokeScript("DisplayName", New Object() {"dotnetcurry"})
      End If
End Sub
 
Step 5: The final step is to navigate to the page on the button click:
C#
private void btnBrowse_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate("file://D:/TestPage.html");
}
VB.NET
Private Sub btnBrowse_Click(ByVal sender As Object, ByVal e As EventArgs)
      webBrowser1.Navigate("file://D:/TestPage.html")
End Sub
 
Run the application and click on the button. The text ‘Welcome dotnetcurry’ will appear if the javascript has been executed successfully. In this short article, we saw how to execute a javascript function from a Windows Form. Just remember that before the javascript is executed, the page elements referenced in the javascript function should have been loaded completely. I hope this article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed.
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Chandan on Wednesday, October 8, 2008 11:37 AM
How do i pass a form parameter by InvokeScript function?
Comment posted by Suprotim Agarwal on Thursday, October 9, 2008 6:02 AM
Chandan: That's been shown in the article

Single parameter:
webBrowser1.Document.InvokeScript("DisplayName", new object[] {"param1"});

Multiple Paramters:
webBrowser1.Document.InvokeScript("DisplayName", new object[] {"param1","param2"});
Comment posted by How would you call an object's method? on Thursday, November 13, 2008 3:07 PM
Suppose your JavaScript contains the following:
var obj = {
    foo: function () { alert('foo'); }
};

How can you call obj.foo?  I tried this but it doesn't work:
webBrowser1.Document.InvokeScript("obj.foo");
Comment posted by Kamran on Friday, January 2, 2009 6:52 PM
Hi

Thanks for the article, it was great.  Any ideas on how I would go the other way.  Call C# functions from javascript and expose C# properties to javascript.

thanks
Comment posted by Me on Monday, January 5, 2009 1:33 PM
"Call C# functions from JavaScript and expose C# properties to JavaScript."

To call a C# function from JavaScript, you need to first set ObjectForScripting (a property of the WebBrowser class) to a visible com object like so:

[ComVisible(true)]
public class ScriptManager
{
    public ScriptManager()
    {
    }

    public void MyFunc()
    {
         MessageBox.Show("MyFunc has been called");
    }
}

So create a WebBrowser control and assign the ScriptManager object you have created and set ObjectForScripting to the ScriptManager object, like so:
WebBrowser wb = new WebBrowser();
wb.ObjectForScripting = new ScriptManager();
wb.Navigate("location here");

Then in JavaScript you need to call this method like so:
     window.external.MyFunc();
Comment posted by Me on Monday, January 5, 2009 1:44 PM
Extension to above comment

The same thing works for other members such as variables and properties
you can create a property in c# like so
public string MyProp
{
   get { return "A string"; }
}

Call it the same way from JavaScript like so
   alert(window.external.MyProp);
Comment posted by ssc707 on Wednesday, January 28, 2009 7:25 PM
what if navigate to a HTML page where you don't know the name of the Javascript function?
Comment posted by adam on Tuesday, March 10, 2009 4:32 PM
I've been looking around the web trying to figure out if it is possible to pass an array from javascript into a public method of the ObjectForScripting class.  My attempts so far have not worked.  If my method takes just a string argument, then it works.  If I change it to take an array and try to call it that way.  Nothing seems to happen.
Comment posted by Poornima .S on Wednesday, April 1, 2009 5:39 AM
I have one 2 js files. i want to use it in my windows application written in c#. In my app i want to convert the text typed in english to hindi..here i have hindi.js which defines the unicode for all the characters. and converter.js contains some functions. i want to use call one function "print_many_words" of converter.js from c# button click..how to go about this? Please help me..i can send yuo the js files also.

Thanks & Regards,
Poornima
Comment posted by Bobby Lundqvist on Tuesday, January 12, 2010 7:20 PM
Thank you!
I've been looking around the web for a code for this, without any luck.. until now!
I need to scrape information from a site where the content is completely javascript generated,
and with this code you saved me ALOT of work!

Cheers mate

Bobby Lundqvist
Comment posted by rowter on Monday, March 22, 2010 3:41 PM
Hi,

I am working with Bing Maps on a windows form. I am using a webbrowser control to host my form.
From the webbrowser on my winform, my code looked like this.

WebBrowser1.Document.InvokeScript("GetRouteMap", New Object() {CObj(addr), CObj(addr2)})
WebBrowser1.Document.InvokeScript("GetMap", New String() {addr, addr2})// I tried all differet formats here.

Now in my javascript:

<body onload="GetMap(primAddr, secnAddr);" style="font-family:Arial">
      <div id;='directions'></div>
   <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
</body>

function GetMap(primAddr,secnAddr)
         {
            map = new VEMap("myMap");
            map.LoadMap();
               //Location = new Array("5717 Ridgemont pl, Midland, TX", "6701 eastridge Rd, Odessa, TX");

               alert("primAddr value is a type of :   " + typeof(primAddr));
               alert("secnAddr value is a type of :   " + typeof(secnAddr));
               //Location = new Array(a,b);

               Location = new (primAddr, secnAddr);
              try{
   alert(Location[0]); ------------------------- Has the values that i passed from my form
                  alert(Location[1]); ------------------------- Has the values that i passed from my form
            GetRouteMap(Location); ----------------Calling this function and passing the array.
             }
            catch (e) {
             alert(e.name + "TestLocation1234" + e.message);
            }
          }
    

function GetRouteMap(Location)
         {
             var options = new VERouteOptions;
             //options.DrawRoute      = true;
             options.RouteCallback  = ShowTurns;
//             options.ShowDisambiguation = false;
             options.DistanceUnit   = VERouteDistanceUnit.Mile;
             var testroute = new VERoute;
             alert(typeof(Location));

             try{
                        alert(Location[0]);  -------------------  Has the values that i passed from my form
                        alert(Location[1]);  -------------------  Has the values that i passed from my form
                 map.GetDirections(Location, options);            -------------Here this function is expecting an array so, i pass the array directly.
                     }
                    else{
                    alert("Location is not an array");
                    }
                    map.GetDirections(Location, options);
                }
            catch (e) {
             alert("GetRouteMethod Erorr:" + e.name + " " + e.message);
                      }
         }



This is failing for some reason. If i hardcode the address values it is working good. But, if i send the parameters, it is failing. Is there any mistake in my code? Not sure why this is erroring out for the parameters. I checked the parameters ad they are of string type.

Any idea what might be wrong?

Thanks

Comment posted by pawan kumar on Tuesday, June 21, 2011 1:41 AM
dear sir
send me javascript function to convert the hindi to english.
accept the value in textbox in hindi and convert in english and display in textbox.
kindly help me sir.as soon as possible send me
Comment posted by Suprotim Agarwal on Tuesday, June 21, 2011 4:15 AM
Pawan: That's a lot of work. So I will give you some pointers to help you out.

Check out the free library at http://unidecode.codeplex.com/

Google API also has a transliteration service but it will stop it's services in Dec 2011, so I won't suggest you use that
Comment posted by fghfgh on Wednesday, July 20, 2011 4:56 AM
hgfhgfhfghgf