使用Web浏览器控件等待Ajax加载

时间:2011-06-22 03:48:22

标签: ajax browser controls

我对.Net& C#,需要通过Web浏览器控件加载Ajax页面的帮助。

这是我正在使用的代码,导航到登录后我正在搜索具有ajax调用的页面。

private void searchNCPPageClick(string msg)
    {
        log.Debug("Processing Navigation to the NCP Search Project page...");
        try
        {
            HtmlElementCollection elems = this.webBrNcp.Document.GetElementsByTagName("html")[0].All;                
            foreach (HtmlElement elem in elems)
            {
                if (!(elem.DomElement.GetType().ToString().Equals("mshtml.HTMLAnchorElementClass")))
                {
                    continue;
                }

                if (elem.InnerHtml != null && elem.InnerHtml.Equals(IConstants.STR_SEARCH_PROJECT))
                {
                    elem.InvokeMember("click");

                    waitTillLoad(this.webBrNcp);
                    this.m_pageStatus = true;                        
                    this.m_page = this.webBrNcp.Document.GetElementsByTagName("html")[0].OuterHtml;
                    break;
                }
            }
            log.Debug("The Search Project Page navigated successfully.");
        }catch(Exception ex)
        {                
            log.Error("Error occurred while navigating Search Project page =" + ex.Message);
            string errMsg = String.Format("Error occurred while navigating Search Project page in {0} - {1}", "searchNCPPageClick", ex.Message);
            throw new ScreenScrapeException(errMsg, ex);
        }
    }

方法waitTillLoad取自this

private void waitTillLoad(WebBrowser webBrControl)         {

        WebBrowserReadyState loadStatus;
        //wait till beginning of loading next page 
        int waittime = 100000;
        int counter = 0;
        while (true)
        {
            loadStatus = webBrControl.ReadyState;

            Application.DoEvents();

            if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
            {
                break;
            }
            counter++;
        }       

        //wait till the page get loaded.
        counter = 0;
        while (true)
        {               
            loadStatus = webBrControl.ReadyState;
            Application.DoEvents();

            if (loadStatus == WebBrowserReadyState.Complete && webBrControl.IsBusy != true)
            {
                break;
            }
            counter++;
        }
    }

这很好用,但我想知道确定ajax请求的确切加载时间。

1 个答案:

答案 0 :(得分:0)

你试过Watin吗?它是一个免费的库,可以帮助您在使用Web浏览器时监控ajax

你可以在堆栈上查看this答案