2

I want to call a JavaScript function through C#, using a WinForm's WebBrowser control. I've attempted to search however could not find anything which answers my question, only solutions which involved ASP.NET.

Thank you in advance.


Edit:

This is the only question regarding this that I've found that actually has an answer that demonstrates how to call a JavaScript method with parameters, and also shows how to call a .NET function from JavaScript in the WebBrowser control.

I do not think this question should be marked as a duplicate as it adds good value. It's the first hit on a google search for "c# webbrowser call javascript function with parameters".

Hein Andre Grønnestad
  • 6,885
  • 2
  • 31
  • 43
seven_swodniw
  • 881
  • 3
  • 9
  • 15

1 Answers1

7

This is a nice example, that I found here:

http://www.codeproject.com/Tips/127356/Calling-JavaScript-function-from-WinForms-and-vice

HTML/JavaScript

<html>
     <head>
          <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>

C#

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());
        }
    }
}
Hein Andre Grønnestad
  • 6,885
  • 2
  • 31
  • 43
themhz
  • 8,335
  • 21
  • 84
  • 109
  • 4
    Thank you very much.This answer includes how to call a javascript function passing parameters to it whereas your first one in the comment did not.Should you be intelligent to post a question? – seven_swodniw Mar 27 '12 at 18:02
  • If you want to pass objects rather than strings use dynamic: https://social.msdn.microsoft.com/Forums/vstudio/en-US/01cf9667-b420-4c82-a2ba-18b996eac7e2/pass-arrays-from-javascript-to-c-via-webbrowser-object?forum=wpf – David Wilton Feb 08 '17 at 08:58