WebBrowser.Navigate just… Isn't

2019-08-30 07:26发布

问题:

I have this code:

private void goButton_Click(object sender, EventArgs e)
{
    web.Navigate(loginURL.Text + "/auth/login");
}

I have the browser showing, and it's just not navigating... It doesn't navigate etc.

The URL is valid.

回答1:

MSDN is your friend. Make sure you have the 'http://' prefix and try using the Navigate(Uri url) overload.

// Navigates to the given URL if it is valid. 
private void Navigate(String address)
{
    if (String.IsNullOrEmpty(address)) 
         return;

    if (address.Equals("about:blank")) 
         return;

    if (!address.StartsWith("http://") && !address.StartsWith("https://"))
    {
        address = "http://" + address;
    }
    try
    {
        webBrowser.Navigate(new Uri(address));
    }
    catch (System.UriFormatException)
    {
        return;
    }
}


回答2:

You need to handle DocumentCompleted event of web browser.

Go through following code:

  private void goButton_Click(object sender, EventArgs e)
    {
      WebBrowser wb = new WebBrowser();
      wb.AllowNavigation = true;

      wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

      wb.Navigate(loginURL.Text + "/auth/login");

              }

    private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
      WebBrowser wb = sender as WebBrowser;
      // wb.Document is not null at this point
    }