Waiting for WebBrowser ajax content

前端 未结 4 1296
感动是毒
感动是毒 2021-02-14 14:21

I want to pause the execution of my thread until a particular div has been loaded via ajax into a WebBrowser instance. Obviously I can continuously check for the presence of thi

相关标签:
4条回答
  • 2021-02-14 14:35

    You should not call Thread.Sleep as it will block the UI thread.

    A better solution is to create an asynchronous task. Inside this task you can call Task.Delay which won't interfere with the UI.

    static async Task<IHTMLElement> WaitForElement(WebBrowser browser, string elementID, TimeSpan timeout)
    {
        long startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        var timeoutMS = timeout.TotalMilliseconds;
    
        // While the timeout has not passed...
        while (DateTimeOffset.Now.ToUnixTimeMilliseconds() - startTime < timeoutMS)
        {
            // Wait for 200ms
            await Task.Delay(TimeSpan.FromMilliseconds(200));
    
            // Check if the document contains the element
            var document = (HTMLDocument) browser.Document;
            var element = document.getElementById(elementID);
            if (element != null)
            {
                // Element found, stop looping
                return element;
            }
        }
    
        throw new Exception($"Element was not loaded after {timeoutMS} milliseconds");
    }
    

    The code above checks the DOM every 200 milliseconds to see if the element with the given ID exists. It also contains a timeout (e.g. 10 seconds) in case the element never gets loaded for any unexpected reason.

    Here is an example showing how to use this function to read the value out of a text field added to the document after an AJAX call:

    var input = (IHTMLInputElement) await WaitForElement(myBrowserControl, "input-id", TimeSpan.FromSeconds(10));
    var value = input.value; // Read the value of the input field
    
    0 讨论(0)
  • 2021-02-14 14:42

    Don't block the main thread's message pump. Since the browser is an STA component, xmlhttprequest won't be able to raise events from the background thread if you block the message pump. You can't navigate in a background thread. The Windows Forms wrapper of the webbrowser ActiveX does not support access from other threads than the UI thread. Use a timer instead.

    0 讨论(0)
  • 2021-02-14 14:51

    You can find a text into body for example:

    while (HtmlWindow.Document.Body.InnerHtml.Contains(some_text) == false)
    {        
        Application.DoEvents();
        Thread.Sleep(200);
    }
    
    0 讨论(0)
  • 2021-02-14 14:59

    The following should work,

    while (Browser.Document.GetElementById("divid") == null) 
    { 
        Application.DoEvents();
        Thread.Sleep(200); 
    }
    

    The above worked for me...

    0 讨论(0)
提交回复
热议问题