小编典典

从WebBrowser中的文档中的JavaScript调用C#代码

c#

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

我知道可以使用InvokeScript调用JavaScript函数,但是如何从文档中的
JavaScript调用C#代码?由于安全性,我想这并不容易,但是无论如何,有可能吗?这些JavaScript函数应该是用户函数,就像宏一样,它们可以告诉WebBrowser在自己编写的整个C#库的帮助下确切地做什么。而且由于这是用于Web爬虫的,因此JavaScript是这些宏的理想语言,因为它几乎可以用来访问HTML文档中的元素。


阅读 324

收藏
2020-05-19

共1个答案

小编典典

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

这是一个包含文档和简单示例的页面:http
//msdn.microsoft.com/zh-
cn/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" });
    }
}
2020-05-19