C# 在浏览器控件上自动登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19385840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
auto login on webbrowser control
提问by Latex Person
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?
我正在创建一个带有自动登录站点的 Webbrowser 控件的表单。当我调试它时,我可以看到它启动到站点并填写用户名和密码就好了,但是一旦它登录,它就会再次通过相同的代码,因此导致错误,因为它找不到相同的元素。为什么程序会循环遍历这段代码?我是否将代码输入到错误的事件处理程序中?
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");
}
}
}
采纳答案by SLaks
The DocumentCompleted
event fires whenever anydocument finishes loading.
After you log in, the event fires again when you load the next page.
DocumentCompleted
每当任何文档完成加载时都会触发该事件。
登录后,当您加载下一页时,该事件将再次触发。
You should check the URL and only perform the auto-login if you're at the actual login page.
您应该检查 URL,并且仅当您在实际登录页面时才执行自动登录。
(and make sure not to auto-login if a phisher sends your app a fake login page to steal the user's password)
(如果网络钓鱼者向您的应用发送虚假登录页面以窃取用户密码,请确保不要自动登录)
回答by Hessy SharpSabre
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
}
}
}
}