I'm really struggling to grasp the logic behind this function I'm working on.
public void PortalLogin(AutoResetEvent signal)
{
// Navigate to portal
string portalUrl = "website_name";
string portalEmail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cca9a1ada5a08ca9a1ada5a0e2afa3a1">[email protected]</a>";
string portalPassword = "password";
Action action2 = () =>
{
webBrowser2.Tag = signal;
webBrowser2.Navigate(portalUrl);
webBrowser2.DocumentCompleted -= WebBrowserDocumentCompleted;
webBrowser2.DocumentCompleted += WebBrowserDocumentCompleted;
};
webBrowser2.Invoke(action2);
signal.WaitOne();
// Login to O365 portal
webBrowser2.Invoke(new Action(() =>
{
HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript = webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)testScript.DomElement;
element.text = "function PortalLogin() { document.getElementById('userid').value = '" + portalEmail + "'; document.getElementById('password').value = '" + portalPassword + "'; document.getElementById('login').submit(); }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("PortalLogin");
}));
}
... more functions after this
As I debug, it appears that the
document.getElementById('login').submit();
part of the script is not being executed at the right moment. How can I ensure that nothing proceeds until the InvokeScript
has been fully completed?
If there are any unnecessary lines of code or areas that can be tidied up, I would greatly appreciate any feedback on that too.
UPDATE: Below is the DocumentCompleted function.
private void WebBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs Url)
{
((AutoResetEvent)((WebBrowser)sender).Tag).Set();
}