Calling a Javascript function in the C# webBrowser

2019-01-07 21:21发布

I am using the webBrowser control 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 InvokeScript method, and I tried a lot, but everything has failed.

2条回答
家丑人穷心不美
2楼-- · 2019-01-07 21:38

Can you specify what failed?

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

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

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");
        }
    }
查看更多
爷、活的狠高调
3楼-- · 2019-01-07 21:43

You can send arguments to the js function:

// 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"});
    }
}
查看更多
登录 后发表回答