65.9K
CodeProject 正在变化。 阅读更多。
Home

从在 WebBrowser 中托管的 JavaScript 调用 C# 方法

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.93/5 (19投票s)

2010年11月23日

CPOL
viewsIcon

176907

本示例演示了如何从在 Windows 窗体应用程序中托管的 WebBrowser 控件内的网页中的 JavaScript 调用 C# 方法。

此示例演示了如何从 JavaScript 调用 C#。它还表明可以向 C# 方法传递参数。首先,创建一个 Windows 窗体应用程序。然后,将 WebBrowser 控件添加到您的窗体。然后修改窗体的代码,使其如下所示
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>";
        }
    }
}
请注意,您的应用程序可能属于除 WindowsFormsApplication6 之外的其他命名空间,但如果您严格按照上述说明操作,其余代码应该可以正常工作。我创建这个技巧/窍门是因为有人向我提出了一个问题,他们不理解 这个示例 我发送给他们。通过修复我发现的两个错误、添加未提及的 using 语句以及对代码进行大量注释,这个技巧/窍门使示例更容易理解。希望你们其他人也会觉得它有用。
© . All rights reserved.