-2

I need to navigate to a certain url using a webBrowser1 in my form and performing certain operations:

webBrowser1.Url = new Uri(@url);
webBrowser1.Navigate(new Uri(@url));
var state = webBrowser1.ReadyState;

        HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("a");

        foreach (HtmlElement link in links)
        {
            if (link.InnerText != null)
            {
                if (link.InnerText.Equals("Log in"))
                {
                    link.InvokeMember("Click");
                    webBrowser1.Document.GetElementById("templateLoginPopupUsername").InnerText = username;
                    HtmlElementCollection input = webBrowser1.Document.GetElementsByTagName("input");
                    foreach (HtmlElement item in webBrowser1.Document.All)
                    {
                        if (item.Name == "password")
                        {
                            item.InnerText = password;
                            break;
                        }
                    }
                    break;
                }
            }
        }

the page only loads when the code is entirely done executing, so I can't perform any operations on it. Is there any way to force the browser to load?

Simon
  • 73
  • 1
  • 1
  • 6

1 Answers1

0

First of all, your code will crash before it reaches the loop. webBrowser1.Document object might not be available if the page requested does not load on time. You should do this looping once the document has finished loading i.e. create an event handler such as this one

protected void DocumentCompletedHandler(Object sender, EventArgs e)
{
//Your code here
}

Then, to attach this handler to your webBrowser1 object, use
webBrowser1.DocumentCompleted +=DocumentCompletedHandler;

but even this might not work in some cases(see this).

Also, your code seems to be intended for malicious purposes. You should not do this.

Community
  • 1
  • 1
Transcendental
  • 983
  • 2
  • 11
  • 27