I need to click an html button and navigate to another page. After click I need to wait for page loading, and go to the new page only when the old page loaded.
Here is the code, that click a button:
element = webBrowser1.Document.GetElementById("LoginButton");
element.InvokeMember("click");
webBrowser has got a IsBusy property, but it don`t works after button click:
element = webBrowser1.Document.GetElementById("LoginButton");
element.InvokeMember("click");
if(webBrowser1.IsBusy)
{
MessageBox.Show("Busy"); // Nothing happens, but page is not full loaded.
}
If I add System.Threading.Thread.Sleep(1000)
the page loads and I can go to next page, but page loading time on other computers can be more.
What can I do to load another page only after the previous page has loaded?
P.S: I am from Russia, so sorry for bad English.
If your webpage has any javascript blocks, you won't be able to solve the problem using the WebBrowser control itself. You should wait for a document.ready event using javascript code and let know your C# program about it.
Previously, I made a javascript block that provides the webpage state. It looks like this:
var isBusy = true;
function getIsScriptBusy () {
return isBusy;
}
// when loading is complete:
// isBusy = false;
// document.ready event, for example
and a C# code that waits for it to return true:
void WaitForCallback(int timeout) {
Stopwatch w = new Stopwatch();
w.Start();
Wait(delegate() {
return (string)Document.InvokeScript("getIsScriptBusy") != "false"
&& (w.ElapsedMilliseconds < timeout || Debugger.IsAttached);
});
if(w.ElapsedMilliseconds >= timeout && !Debugger.IsAttached)
throw new Exception("Operation timed out.");
}
void Wait(WaitDelegate waitCondition) {
int bRet;
MSG msg = new MSG();
while(waitCondition() && (bRet = GetMessage(ref msg, new HandleRef(null, IntPtr.Zero), 0, 0)) != 0) {
if(bRet == -1) {
// handle the error and possibly exit
} else {
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
Thread.Sleep(0);
}
}
There are lots of events exposed by the WebBrowser
control. You might try Navigated
or DocumentCompleted
.
Nick
WebBrowser.Navigated
is the browser event you are seeking.
Use this ,
You might just be able to use this once
br1.DocumentCompleted += br1_DocumentCompleted;
Application.Run();
Call
void br1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br1 = sender as WebBrowser;
if (br1.Url == e.Url)
{
Console.WriteLine("Natigated to {0}", e.Url);
Application.ExitThread(); // Stops the thread
}
}
Replace br1 with your webbrowser name
Hope this helps