我在 C# 中使用webBrowser控件加载网页,需要调用返回字符串值的 JavaScript 函数。我得到了一个使用InvokeScript方法的解决方案,我尝试了很多,但一切都失败了。
在 C# webBrowser 控件中调用 Javascript 函数
IT技术
c#
.net
javascript
controls
webbrowser-control
                    2021-03-02 11:50:39
                
                    
                
            
        2个回答
            你能说明什么失败了吗?
下面的示例包含一个带有 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"});
    }
}