gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:12:49 31 4
gpt4 key购买 nike

我正在使用 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com