.NET C#:WebBrowser控件Navigate()不加载目标URL

Dav*_*ave 15 .net c# browser controls navigateurl

我正在尝试以编程方式通过WebBrowser控件加载网页,目的是测试页面及其JavaScript函数.基本上,我想比较通过此控件运行的HTML和JavaScript与已知输出,以确定是否存在问题.

但是,我在创建和导航WebBrowser控件时遇到了麻烦.下面的代码旨在将HtmlDocument加载到WebBrowser.Document属性中:

WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;

wb.Navigate("http://www.google.com/");
Run Code Online (Sandbox Code Playgroud)

在Navigate()运行后通过Intellisense检查Web浏览器的状态时,WebBrowser.ReadyState为'未初始化',WebBrowser.Document = null,并且它总体上看起来完全不受我的调用的影响.

在上下文中,我在Windows窗体对象之外运行此控件:我不需要加载窗口或实际查看页面.要求规定需要简单地执行页面的JavaScript并检查生成的HTML.

非常感谢任何建议,谢谢!

Chr*_*lor 16

您应该处理WebBrowser.DocumentComplete事件,一旦该事件被引发,您将拥有Document等.

wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
Run Code Online (Sandbox Code Playgroud)


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

这是一个完整的示例,我在Windows窗体应用程序中快速完成并进行了测试.

public partial class Form1 : Form
  {
    public Form1()
    {      
      InitializeComponent();
    }

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

      wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

      wb.Navigate("http://www.google.com");

              }

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

编辑:这是一个从控制台应用程序运行窗口的简单代码版本.您当然可以进一步将事件公开给控制台代码等.

using System;
using System.Windows;
using System.Windows.Forms;

namespace ConsoleApplication1
{
  class Program
  {    
    [STAThread] 
    static void Main(string[] args)
    {      
      Application.Run(new BrowserWindow());   

      Console.ReadKey();
    }
  }

  class BrowserWindow : Form
  {
    public BrowserWindow()
    {
      ShowInTaskbar = false;
      WindowState = FormWindowState.Minimized;
      Load += new EventHandler(Window_Load);
    }

    void Window_Load(object sender, EventArgs e)
    {      
      WebBrowser wb = new WebBrowser();
      wb.AllowNavigation = true;
      wb.DocumentCompleted += wb_DocumentCompleted;
      wb.Navigate("http://www.bing.com");      
    }

    void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
      Console.WriteLine("We have Bing");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)