我在C#中使用 webBrowser 控件加载网页,需要调用返回字符串值的JavaScript函数。我有一个使用 InvokeScript 方法的解决方案,我尝试了很多,但一切都失败了。

有帮助吗?

解决方案

你能说明失败了吗?

下面的示例包含一个带有WebBrowser和Button的表单。

最后称为y的对象有句子“我做了!”。所以和我一起工作。

public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            webBrowser1.DocumentText = @"<html><head>
                <script type='text/javascript'>
                    function doIt() {
                        alert('hello again');
                        return 'i did it!';
                    }
                </script>
                </head><body>hello!</body></html>";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            object y = webBrowser1.Document.InvokeScript("doIt");
        }
    }

其他提示

您可以向js函数发送参数:

// don't forget this:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        webBrowser1.DocumentText = @"<html><head>
            <script type='text/javascript'>
                function doIt(myArg, arg2, arg3) {
                    alert('hello again ' + myArg);
                    return 'yes '+arg2+' - you did it! thanks to ' +myArg+ ' & ' +arg3;
                }
            </script>
            </head><body>hello!</body></html>";

    }

    private void button1_Click(object sender, EventArgs e)
    {
        // get the retrieved object from js into object y
        object y = webBrowser1.Document.InvokeScript("doIt", new string[] { "Snir", "Raki", "Gidon"});
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top