How to call and pass arguments to a JavaScript met

2020-07-30 04:27发布

问题:

This question already has answers here:
Closed 8 years ago.

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".

回答1:

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());
        }
    }
}