从WebBrowser中的Document中的JavaScript调用C#代码

Jua*_*uan 35 .net javascript c#

我有一个C#WinForms应用程序,里面有一个WebBrowser控件.我想在嵌入式Web浏览器控件中执行C#表单和JavaScript之间的双向通信.

我知道我可以使用InvokeScript调用JavaScript函数,但是如何从Document中的 JavaScript调用C#代码?我想由于安全性而不容易,但无论如何,它有可能吗?这些JavaScript函数应该是用户函数,就像宏一样,它会告诉WebBrowser在我自己编写的整个C#库的帮助下究竟该怎么做.由于这是一个Web scraper,因此JavaScript是这些宏的完美语言,因为它几乎可以访问HTML文档中的元素.

Gab*_*abe 50

您需要做的是将ObjectForScriptingWeb浏览器控件上的属性设置为包含要从JavaScript调用的C#方法的对象.然后,您可以使用JavaScript从JavaScript访问该对象window.external.唯一需要注意的是对象必须具有该[ComVisibleAttribute(true)]属性.我成功地用了好几年了.

这是一个包含文档和简单示例的页面:http://msdn.microsoft.com/en-us/library/a0746166.aspx

这是链接中的示例(我还没有尝试过这段代码):

using System;
using System.Windows.Forms;
using System.Security.Permissions;

[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
    private WebBrowser webBrowser1 = new WebBrowser();
    private Button button1 = new Button();

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    public Form1()
    {
        button1.Text = "call script code from client code";
        button1.Dock = DockStyle.Top;
        button1.Click += new EventHandler(button1_Click);
        webBrowser1.Dock = DockStyle.Fill;
        Controls.Add(webBrowser1);
        Controls.Add(button1);
        Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.AllowWebBrowserDrop = false;
        webBrowser1.IsWebBrowserContextMenuEnabled = false;
        webBrowser1.WebBrowserShortcutsEnabled = false;
        webBrowser1.ObjectForScripting = this;
        // Uncomment the following line when you are finished debugging.
        //webBrowser1.ScriptErrorsSuppressed = true;

        webBrowser1.DocumentText =
            "<html><head><script>" +
            "function test(message) { alert(message); }" +
            "</script></head><body><button " +
            "onclick=\"window.external.Test('called from script code')\">" +
            "call client code from script code</button>" +
            "</body></html>";
    }

    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Document.InvokeScript("test",
            new String[] { "called from client code" });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您还应该注意从声明为public的JavaScript调用的C#方法. (4认同)

blu*_*ucz 5

您可能正在寻找http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx

WebBrowser.ObjectForScripting允许您将[ComVisible] .net类的实例公开给在托管Web浏览器中运行的javascript代码。它在javascript中显示为window.external

Microsoft的优秀文章: 如何:在DHTML代码和客户端应用程序代码之间实现双向通信