How to use WebBrowser control DocumentCompleted event in C#?

前端 未结 5 1403
野性不改
野性不改 2020-11-27 16:14

Before starting writing this question, i was trying to solve following

// 1. navigate to page
// 2. wait until page is downloaded
// 3. read and write some d         


        
5条回答
  •  無奈伤痛
    2020-11-27 17:01

    Just thought to drop a line or two here about a small improvement which works in conjunction with the code of FeiBao. The idea is to inject a landmark (javascript) variable in the webpage and use that to detect which of the subsequent DocumentComplete events is the real deal. I doubt it's bulletproof but it has worked more reliably in general than the approach that lacks it. Any comments welcome. Here is the boilerplate code:

     void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url = e.Url.ToString();
            var browser = (WebBrowser)sender;
    
            if (!(url.StartsWith("http://") || url.StartsWith("https://")))
            {
                // in AJAX     
            }
            if (e.Url.AbsolutePath != this.webBrowser.Url.AbsolutePath)
            {
                // IFRAME           
            }
            else if (browser.Document != null && (bool)browser.Document.InvokeScript("eval", new object[] { @"typeof window.YourLandMarkJavascriptVariableHere === 'undefined'" }))
            {
                ((IHTMLWindow2)browser.Document.Window.DomWindow).execScript("var window.YourLandMarkJavascriptVariableHere = true;");
    
                // REAL DOCUMENT COMPLETE
                // Put my code here
            }
        }
    

提交回复
热议问题