Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for WebBrowser ajax content

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 this div doing something like:

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

However, sleeping the thread that the Browser is in between loops only blocks the browser from actually loading the content in the first place. It seems, therefore, that I need to execute the Browser.Navigate method in a separate thread - I can then continue to check/wait for the presence of the div whilst the WebBrowser instance continues loading the URL I asked it to.

My attempts at this, however, have failed and I'd value any input on how I should go about this. I thought simply dispatching a new thread with new Thread(() => { Browser.Navigate(url); }); would work but after doing so, nothing loads and the Browser.ReadyState remains as 'Uninitialized'. I presume I'm misunderstanding how to go about properly threading procedures like this with C# and would value some advice!

like image 824
JoeR Avatar asked Sep 25 '10 16:09

JoeR


2 Answers

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.

like image 74
Sheng Jiang 蒋晟 Avatar answered Nov 15 '22 13:11

Sheng Jiang 蒋晟


The following should work,

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

The above worked for me...

like image 23
Ponson Avatar answered Nov 15 '22 12:11

Ponson