The documentation for the webbrowser in WinForms specifies you can invoke events like this:
webBrowser1.Document.GetElementById("signin").InvokeMember("click");
..but it doesn't work for me. I tried a hack:
HtmlElement element = webBrowser1.Document.CreateElement("script");
element.InnerText = "function SubmitForm() { document.getElementById('signin').click(); }";
webBrowser1.Document.Forms[0].AppendChild(element);
webBrowser1.Document.InvokeScript("SubmitForm");
..which didn't work either. However, another hack:
HtmlElement element = webBrowser1.Document.CreateElement("script");
element.InnerText = "function SubmitForm() { alert('Click me!');
document.getElementById('signin').click(); }";
webBrowser1.Document.Forms[0].AppendChild(element);
webBrowser1.Document.InvokeScript("SubmitForm");
..worked perfectly. Except there is user intervention to click the alert box, which I don't want. Is this some kind of race condition? The code is executed in webBrowser1_DocumentCompleted so it should be fine. If you have a way to successfully trigger the event, please do tell.
@Jimi here's the code you requested:
private void Form1_Load(object sender, EventArgs e)
{
string targetUrl = "https://banking.westpac.com.au/wbc/banking/handler?TAM_OP=login&URL=%2Fsecure%2Fbanking%2Foverview%2Fdashboard";
webBrowser1.Navigate(targetUrl);
}
private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted_1;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted_2;
webBrowser1.Document.GetElementById("fakeusername").InnerText = "andy";
webBrowser1.Document.GetElementById("password").InnerText = "password";
//webBrowser1.Document.GetElementById("signin").InvokeMember("click");
HtmlElement element = webBrowser1.Document.CreateElement("script");
element.InnerText = "function SubmitForm() { setTimeout(function() { document.getElementById('signin').click(); }, 5000); }";
webBrowser1.Document.Forms[0].AppendChild(element);
webBrowser1.Document.InvokeScript("SubmitForm");
}
The alert makes it work (so does setTimeout). It seems like the document is not really completed, but the browser thinks it is. Could JS on the page do that?