I am creating a form with a Webbrowser control that automatically logs in to a site. When I debug it, I can see that it launches to the site and fill the username and password just fine, but once it's logged in, it's going through the same code again, hence causing error as it cannot find the same elements. Why is the program looping through this code? Did I enter the code to the wrong event handler?
namespace MyProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement username = doc.GetElementById("UserName");
HtmlElement password = doc.GetElementById("Password");
HtmlElement submit = doc.GetElementById("submit");
username.SetAttribute("value", "XXXXXXXX");
password.SetAttribute("value", "YYYYYYYYYY");
submit.InvokeMember("click");
}
}
}
The DocumentCompleted event fires whenever any document finishes loading.
After you log in, the event fires again when you load the next page.
You should check the URL and only perform the auto-login if you're at the actual login page.
(and make sure not to auto-login if a phisher sends your app a fake login page to steal the user's password)
namespace MyProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool is_sec_page = false;
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!is_sec_page)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement username = doc.GetElementById("UserName");
HtmlElement password = doc.GetElementById("Password");
HtmlElement submit = doc.GetElementById("submit");
username.SetAttribute("value", "XXXXXXXX");
password.SetAttribute("value", "YYYYYYYYYY");
submit.InvokeMember("click");
is_sec_page = true;
}
else
{
//intract with sec page elements with theire ids and so on
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With