在 C# webBrowser 控件中调用 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1437251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:31:52  来源:igfitidea点击:

Calling a Javascript function in the C# webBrowser control

c#.netjavascriptcontrolswebbrowser-control

提问by raki

I am using the webBrowsercontrol in C# to load a webpage and need to call a JavaScript function that returns a string value. I got a solution to use the InvokeScriptmethod, and I tried a lot, but everything has failed.

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

采纳答案by Gidon

Can you specify what failed?

你能说明什么失败了吗?

My sample below consists of a form with a WebBrowser and a Button.

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

The object called y in the end has the sentence "i did it!". So with me it works.

最后称为 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");
        }
    }

回答by snir

You can send arguments to the js function:

您可以向 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"});
    }
}