web-dev-qa-db-fra.com

Appel d'une fonction Javascript dans le contrôle C # webBrowser

J'utilise le contrôle webBrowser en C # pour charger une page Web et j'ai besoin d'appeler une fonction JavaScript qui renvoie une valeur de chaîne. J'ai obtenu une solution pour utiliser la méthode InvokeScript, et j'ai beaucoup essayé, mais tout a échoué.

26
raki

Pouvez-vous préciser ce qui a échoué?

Mon exemple ci-dessous se compose d'un formulaire avec un WebBrowser et un bouton.

L'objet appelé y à la fin a la phrase "je l'ai fait!". Donc avec moi ça marche.

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");
        }
    }
34
Gidon

Vous pouvez envoyer des arguments à la fonction 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"});
    }
}
6
snir