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

Calling JavaScript function from WinForms and vice-versa

Rate me:
Please Sign up or sign in to vote.
4.88/5 (35 votes)
14 Nov 2010CPOL1 min read 154.6K   38   26
I'be been working on application that needs to load page and display it in WebBrowser control. Second requirement was to allow interaction between WinForms application and web page. After a couple of minutes of googling I found some important information that helped me to solve my problem. Here I will show a sample application where JavaScript function is called from WinForms application.

Hole process can be described by following steps:

  • Create Windows Forms application
  • Add WebBrowser control into Form
  • Create web page with JavaScript function you want to call

Calling JavaScript function from WinForms application isn't so difficult. WebBrowser constrol has property Document which gets an HtmlDocument representing the Web page currently displayed in the WebBrowser control.

You can use this property, in combination with the ObjectForScripting property, to implement two-way communication between a Web page displayed in the WebBrowser control and your application. Use the HtmlDocument.InvokeScript method to call script methods implemented in a Web page from your client application code. Your scripting code can access your application through the window.external object, which is a built-in DOM object provided for host access, and which maps to an object that you specify for the ObjectForScripting property.

XML
<html>
     <head>
          <title></title>
          <script type="text/javascript">
          function ShowMessage(message)
          {
               alert(message);
          }
          function ShowWinFormsMessage() {
               var msg = document.getElementById('txtMessage').value;
               return window.external.ShowMessage(msg);
          }
          </script>
     </head>
     <body>
          <input type="text" id="txtMessage" />
          <input type="button" value="Show Message" onclick="ShowWinFormsMessage()" />
     </body>
</html>

Two JavaScript functions are in sample page. function ShowMessage(message) is called from WinForms application and function ShowWinFormsMessage call ShowMessage(msg) C# function.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WebBrowserJavaScriptExample
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            webBrowser1.ObjectForScripting = new ScriptManager(this);
        }
        private void btnShowMessage_Click(object sender, EventArgs e)
        {
            object[] o = new object[1];
            o[0]=txtMessage.Text;
            object result = this.webBrowser1.Document.InvokeScript("ShowMessage", o);
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Navigate(@"E:\Projects\2010\WebBrowserJavaScriptExample\WebBrowserJavaScriptExample\TestPage.htm");
        }
        [ComVisible(true)]
        public class ScriptManager
        {
            frmMain _form;
            public ScriptManager(frmMain form)
            {
                _form = form;
            }
            public void ShowMessage(object obj)
            {
                MessageBox.Show(obj.ToString());
            }
        }
    }
}

License

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


Written By
Architect Marwin Cassovia Soft
Slovakia Slovakia
My name is Robert Kanasz and I have been working with ASP.NET, WinForms and C# for several years.
MCSD - Web Applications
MCSE - Data Platform
MCPD - ASP.NET Developer 3.5
- Web Developer 4
MCITP - Database Administrator 2008
- Database Developer 2008
MCSA - SQL Server 2012
MCTS - .NET Framework 3.5, ASP.NET Applications
- SQL Server 2008, Database Development
- SQL Server 2008, Implementation and Maintenance
- .NET Framework 4, Data Access
- .NET Framework 4, Service Communication Applications
- .NET Framework 4, Web Applications
MS - Programming in HTML5 with JavaScript and CSS3 Specialist

Open source projects: DBScripter - Library for scripting SQL Server database objects


Please, do not forget vote

Comments and Discussions

 
QuestionCould you help me with this. Pin
Member 106105751-Nov-17 17:09
Member 106105751-Nov-17 17:09 
GeneralMy vote of 5 Pin
JulianPa18-Sep-16 18:24
JulianPa18-Sep-16 18:24 
AnswerBetter way: Use the Windows Scripting Control Pin
Dasiths28-Feb-16 17:15
Dasiths28-Feb-16 17:15 
QuestionC# call javascript Pin
nuaaydh14-Jan-16 19:33
nuaaydh14-Jan-16 19:33 
Questionmy QUESTION.. Pin
bentroy25-Nov-13 17:11
bentroy25-Nov-13 17:11 
GeneralMy vote of 5 Pin
Pablo Aliskevicius20-Jun-13 1:22
Pablo Aliskevicius20-Jun-13 1:22 
GeneralRe: My vote of 5 Pin
Kanasz Robert21-Jun-13 22:22
professionalKanasz Robert21-Jun-13 22:22 
Questionthanks great job Pin
mrx10012-May-12 7:45
mrx10012-May-12 7:45 
AnswerRe: thanks great job Pin
Kanasz Robert21-Jun-13 22:23
professionalKanasz Robert21-Jun-13 22:23 
GeneralReason for my vote of 5 Thx. Pin
Pranit Kothari2-Jan-12 14:56
Pranit Kothari2-Jan-12 14:56 
GeneralReason for my vote of 5 good job man Pin
ronen4415-Nov-10 21:51
ronen4415-Nov-10 21:51 
GeneralThanks for posting this it helped me... Pin
Your Display Name Here19-Apr-11 18:04
Your Display Name Here19-Apr-11 18:04 
GeneralRe: Thanks for posting this it helped me... Pin
Kanasz Robert21-Jun-13 22:23
professionalKanasz Robert21-Jun-13 22:23 
GeneralUsing ScritManager Pin
chaitanyasingh10-Dec-10 20:30
chaitanyasingh10-Dec-10 20:30 
GeneralRe: Using ScritManager Pin
kaminski00117-Jun-13 16:33
kaminski00117-Jun-13 16:33 
QuestionWhat about implementing IActiveScriptSite? Pin
SergeyT216-Nov-10 6:22
SergeyT216-Nov-10 6:22 
QuestionHaving Trouble Testing This - can you help? Pin
dpminusa16-Nov-10 2:21
dpminusa16-Nov-10 2:21 
AnswerRe: Having Trouble Testing This - can you help? Pin
Kanasz Robert16-Nov-10 9:45
professionalKanasz Robert16-Nov-10 9:45 
GeneralRe: Having Trouble Testing This - can you help? Pin
dpminusa16-Nov-10 19:52
dpminusa16-Nov-10 19:52 
GeneralRe: Having Trouble Testing This - can you help? Pin
Kanasz Robert16-Nov-10 20:50
professionalKanasz Robert16-Nov-10 20:50 
GeneralRe: Having Trouble Testing This - can you help? Pin
dpminusa16-Nov-10 20:59
dpminusa16-Nov-10 20:59 
GeneralRe: Having Trouble Testing This - can you help? Pin
Kanasz Robert16-Nov-10 21:19
professionalKanasz Robert16-Nov-10 21:19 
GeneralRe: Having Trouble Testing This - can you help? Pin
dpminusa17-Nov-10 1:00
dpminusa17-Nov-10 1:00 
GeneralRe: Having Trouble Testing This - can you help? Pin
Kanasz Robert17-Nov-10 1:10
professionalKanasz Robert17-Nov-10 1:10 
Hi. I know this states very good :P sometimes is good to take a rest but I understand it is hard when you want to finish something interesting. Thats my problem too. Wink | ;)
btw. I just received you last mail and I will add your images to the article later, now I'm busy.
very good job dan Wink | ;)
GeneralRe: Having Trouble Testing This - can you help? Pin
dpminusa17-Nov-10 1:21
dpminusa17-Nov-10 1:21 

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.