我无法理解我正在构建的此功能的流程。

    public void PortalLogin(AutoResetEvent signal)
            {
                // Navigate to portal
                string portalUrl = "website_name";
                string portalEmail = "[email protected]";
                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


当我逐步执行它时,似乎并没有“及时”调用脚本的document.getElementById('login').submit();部分。如何确保在InvokeScript完全完成之前没有任何反应?

另外-如果您看到任何多余的代码或可以清除的内容,那也很棒。

编辑:这是DocumentCompleted函数。

private void WebBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs Url)
        {
            ((AutoResetEvent)((WebBrowser)sender).Tag).Set();
        }

最佳答案

几点:

您可以在DocumentCompleted外部添加一次PortalLogin事件处理程序,然后重用同一处理程序。您使用的是AutoResetEvent,它会在signal.WaitOne()之后自动重置为非信号状态,因此,只需一个DocumentCompleted永久处理程序就可以了。

您确定document.getElementById('login')返回具有submit方法可用的有效元素吗?调用InvokeScript之前请先进行验证。您可以分两个步骤进行登录,例如:

            element.text = "function PortalLogin() { document.getElementById('userid').value = '" + portalEmail + "'; document.getElementById('password').value = '" + portalPassword + "';  }" +
                "function ExecuteLogin() { document.getElementById('login').submit(); }";
            head.AppendChild(testScript);
            webBrowser2.Document.InvokeScript("PortalLogin");
            // verify document.getElementById('login') here
            webBrowser2.Document.InvokeScript("ExecuteLogin");


注意:如果成功,则提交最终将触发另一个DocumentCompleted事件。

我将使用单线程和await/async pattern重构此代码。 DocumentCompleted可以与TaskCompletionSource(这里是how)一起包装为任务。

下面是使用async/await的外观。在有MessageBox.Show的地方,您可以进行DOM操作。请注意,这都是在主UI线程上完成的(当然是异步完成)。对我来说看起来容易多了。

void Form1_Load(object sender, EventArgs e)
{
    var task = DoNavigationAsync();
    task.ContinueWith((t) =>
    {
        MessageBox.Show("Navigation done!");
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

struct Void {}; // use an empty struct as parameter to generic TaskCompletionSource

async Task DoNavigationAsync()
{
    Void v;
    TaskCompletionSource<Void> tcs = null;
    WebBrowserDocumentCompletedEventHandler documentComplete = null;

    documentComplete = new WebBrowserDocumentCompletedEventHandler((s, e) =>
    {
        // more of DocumentCompleted can possibly be fired due to dynamic navigation inside the web page, we don't want them!
        this.WB.DocumentCompleted -= documentComplete;
        tcs.SetResult(v); // continue from where awaited
    });

    // navigate to www.bing.com
    tcs = new TaskCompletionSource<Void>();
    this.WB.DocumentCompleted += documentComplete;
    this.WB.Navigate("http://www.bing.com");
    await tcs.Task;
    // do whatever you want with this instance of WB.Document
    MessageBox.Show(this.WB.Document.Url.ToString());

    // navigate to www.google.com
    tcs = new TaskCompletionSource<Void>();
    this.WB.DocumentCompleted += documentComplete;
    this.WB.Navigate("http://www.google.com");
    await tcs.Task;
    // do whatever you want with this instance of WB.Document
    MessageBox.Show(this.WB.Document.Url.ToString());

    // navigate to www.yahoo.com
    tcs = new TaskCompletionSource<Void>();
    this.WB.DocumentCompleted += documentComplete;
    this.WB.Navigate("http://www.yahoo.com");
    await tcs.Task;
    // do whatever you want with this instance of WB.Document
    MessageBox.Show(this.WB.Document.Url.ToString());

    return;
}

09-25 15:23