c# - 在 WebBrowser 中调用一个脚本,并等待它完成运行(同步)

标签 c# javascript winforms browser

我正在使用 webBrowser.Document.InvokeScript("Function") 来运行 javascript,它位于使用 Winforms WebBrowser 打开的本地文件中。

问题是,我需要 javascript 在继续之前完成执行。我该如何等待/收听?

这是我的 C# 代码:

    private void Button1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        webBrowser.Document.InvokeScript("Script_A");
        Method_A();
        DialogResult = System.Windows.Forms.DialogResult.OK;
    }

Javascript 代码:

<script>function Script_A() { Script_B(); }</script>

如何确保在 Script_B 完成之前不执行 Method_A?

最佳答案

使用 async/await,您可以等待脚本执行而不会阻塞 UI。

public async void AMethod()
{
    string script =
     @"<script>
        function Script_A() { 
            Script_B(); 
            window.external.Completed(); //call C#: CallbackObject's Completed method
        }
        function Script_B(){
            alert('in script');
        }
    </script>";

    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

    webBrowser1.ObjectForScripting = new CallbackObject(tcs);
    //Ensure DocumentText is loaded before invoking "InvokeScript",
    //by extension method "SetDocumentTextAsync" (below)
    await webBrowser1.SetDocumentTextAsync(script);
    webBrowser1.Document.InvokeScript("Script_A");

    await tcs.Task;

    MessageBox.Show("Script executed");
}


[ComVisible(true)]
public class CallbackObject
{
    TaskCompletionSource<bool> _tcs = null;

    public CallbackObject(TaskCompletionSource<bool> tcs)
    {
        _tcs = tcs;
    }
    public void Completed()
    {
        _tcs.TrySetResult(true);
    }
}

public static class BrowserExtensions
{
    public static Task SetDocumentTextAsync(this WebBrowser wb, string html)
    {
        TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
        WebBrowserDocumentCompletedEventHandler completedEvent = null;
        completedEvent = (sender, e) =>
        {
            wb.DocumentCompleted -= completedEvent;
            tcs.SetResult(null);
        };
        wb.DocumentCompleted += completedEvent;

        wb.ScriptErrorsSuppressed = true;
        wb.DocumentText = html;

        return tcs.Task;
    }
}

关于c# - 在 WebBrowser 中调用一个脚本,并等待它完成运行(同步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691349/

相关文章:

javascript - Ruby on Rails 实时更新

javascript - 将用户链接到 chrome 标志页面

.net - 处理 Me.FormClosing 的两种方法;为什么他们按这个特定顺序开火?

c# - visual studio 2010 c# 类和方法列表

c# - SelectMany 使用 ReactiveExtensions 占用大量内存

javascript - 你能在虚拟元素中创建谷歌地图吗

c# - 如何使事件处理程序中的发件人成为我的自定义控件而不是其中的标签

c# - 尺寸改变时宽度不改变

c# - 登录前握手时出错

c# - 源生成器 : Attribute ConstructorArguments is empty