Click here to Skip to main content
15,867,453 members
Articles / Web Development / HTML
Tip/Trick

Call a C# Method From JavaScript Hosted in a WebBrowser

Rate me:
Please Sign up or sign in to vote.
4.93/5 (22 votes)
6 May 2011CPOL 165.8K   26   32
This demonstrates how you can call a C# method in a Windows Forms application from JavaScript that is hosted in a webpage inside a WebBrowser control on your form.
This sample demonstrates how to call C# from JavaScript. It also shows that parameters can be passed to C# methods.

First, create a Windows Forms application. Then, add a WebBrowser control to your form. Then modify the code for the form so it looks like this:

C#
namespace WindowsFormsApplication6
{
    // This first namespace is required for the ComVisible attribute used on the ScriptManager class.
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    // This is your form.
    public partial class Form1 : Form
    {
        // This nested class must be ComVisible for the JavaScript to be able to call it.
        [ComVisible(true)]
        public class ScriptManager
        {
            // Variable to store the form of type Form1.
            private Form1 mForm;

            // Constructor.
            public ScriptManager(Form1 form)
            {
                // Save the form so it can be referenced later.
                mForm = form;
            }

            // This method can be called from JavaScript.
            public void MethodToCallFromScript()
            {
                // Call a method on the form.
                mForm.DoSomething();
            }

            // This method can also be called from JavaScript.
            public void AnotherMethod(string message)
            {
                MessageBox.Show(message);
            }
        }

        // This method will be called by the other method (MethodToCallFromScript) that gets called by JavaScript.
        public void DoSomething()
        {
            // Indicate success.
            MessageBox.Show("It worked!");
        }

        // Constructor.
        public Form1()
        {
            // Boilerplate code.
            InitializeComponent();

            // Set the WebBrowser to use an instance of the ScriptManager to handle method calls to C#.
            webBrowser1.ObjectForScripting = new ScriptManager(this);

            // Create the webpage.
            webBrowser1.DocumentText = @"<html>
                <head>
	                <title>Test</title>
                </head>
                <body>
	            <input type=""button"" value=""Go!"" onclick=""window.external.MethodToCallFromScript();"" />
                    <br />
                    <input type=""button"" value=""Go Again!"" onclick=""window.external.AnotherMethod('Hello');"" />
                </body>
                </html>";
        }
    }
}

Note that your application may be part of a namespace other than WindowsFormsApplication6, but the rest of the code should work if you follow the above instructions explicitly. I created this tip/trick because somebody asked me a question and they didn't understand this sample that I sent them to. This tip/trick makes the sample more understandable by fixing the two bugs I spotted, adding the using statements that weren't mentioned, and by heavily commenting the code. Hopefully the rest of you will find this of use as well.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
QuestionHow to webbrowser.navigate? Pin
danieleriksson8124-Oct-19 21:33
danieleriksson8124-Oct-19 21:33 
QuestionGecko embedding Pin
yaolixing1-Mar-17 1:47
yaolixing1-Mar-17 1:47 
QuestionIs there a way to call a C# method without using ComVisible Attribute. Pin
Sadanand Reddy17-Mar-15 3:38
Sadanand Reddy17-Mar-15 3:38 
AnswerRe: Is there a way to call a C# method without using ComVisible Attribute. Pin
AspDotNetDev17-Mar-15 4:02
protectorAspDotNetDev17-Mar-15 4:02 
QuestionUnable to Invoke C# Methods in your example. Pin
Member 110498651-Feb-15 23:30
Member 110498651-Feb-15 23:30 
AnswerRe: Unable to Invoke C# Methods in your example. Pin
AspDotNetDev2-Feb-15 16:11
protectorAspDotNetDev2-Feb-15 16:11 
QuestionIncredible Pin
andrewtheart6-Dec-14 21:55
andrewtheart6-Dec-14 21:55 
GeneralMy vote of 5 Pin
Member 36728947-May-14 22:24
Member 36728947-May-14 22:24 
QuestionThank you Pin
Nazz058-Aug-13 10:37
Nazz058-Aug-13 10:37 
Questionhas you tried webkit or xullrunner Pin
pepelepeo12-Mar-12 12:38
pepelepeo12-Mar-12 12:38 
AnswerRe: has you tried webkit or xullrunner Pin
AspDotNetDev12-Mar-12 13:00
protectorAspDotNetDev12-Mar-12 13:00 
GeneralRe: I updated the code so that webBrowser1.DocumentText is set r... Pin
AspDotNetDev6-May-11 4:15
protectorAspDotNetDev6-May-11 4:15 
GeneralRe: I think that you need to call webBrowser1.Document.Write("..... Pin
Anton Levshunov6-May-11 1:08
Anton Levshunov6-May-11 1:08 
GeneralI want to call C# methods using java script in a Mobile Appl... Pin
AUDissa15-Feb-12 0:49
AUDissa15-Feb-12 0:49 
GeneralRe: It's possible. Please see my message in the forum below: htt... Pin
AspDotNetDev15-Feb-12 7:34
protectorAspDotNetDev15-Feb-12 7:34 
GeneralGood tip... Pin
Prasanta_Prince6-May-11 7:03
Prasanta_Prince6-May-11 7:03 
Good tip...
GeneralwebBrowser1 is Uninitialized,so throws a null pointer except... Pin
geaglem5-May-11 17:48
geaglem5-May-11 17:48 
GeneralRe: You are absolutely right, and thank you for the fix. I must ... Pin
AspDotNetDev5-May-11 18:01
protectorAspDotNetDev5-May-11 18:01 
GeneralReason for my vote of 5 Interesting article. Pin
Ángel Manuel García Carmona8-Dec-10 5:14
Ángel Manuel García Carmona8-Dec-10 5:14 
GeneralWow! I didn't realize that this is even possible! Thx! Vote... Pin
n.podbielski1-Dec-10 20:19
n.podbielski1-Dec-10 20:19 
GeneralI am explicilty using Form1 because the ONLY reason ScriptMa... Pin
AspDotNetDev30-Nov-10 4:54
protectorAspDotNetDev30-Nov-10 4:54 
GeneralReason for my vote of 4 Good tip. But why using explicitly F... Pin
sjelen30-Nov-10 2:28
professionalsjelen30-Nov-10 2:28 
GeneralReason for my vote of 5 nice tip. thanks! Pin
Đỗ Hồng Ngọc29-Nov-10 2:26
professionalĐỗ Hồng Ngọc29-Nov-10 2:26 
GeneralReason for my vote of 5 Excellent! Great help for me! Pin
JohnUSA24-Nov-10 13:12
JohnUSA24-Nov-10 13:12 
GeneralHow can i pass a JavaScript variable in C# using a button in... Pin
JohnUSA24-Nov-10 12:31
JohnUSA24-Nov-10 12:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.