简体   繁体   English

如何确保在 CefSharp 中执行 ExecuteScriptAsync

[英]how to be sure that ExecuteScriptAsync is executed in CefSharp

I am using CefSharp component in a Windows Forms C# application.我在 Windows Forms C# 应用程序中使用CefSharp组件。

I load my page in the chromium browser and once loaded, I click a button in it using ExecuteScriptAsync and close the form.我在 chromium 浏览器中加载我的页面,一旦加载,我使用ExecuteScriptAsync单击其中的一个按钮并关闭表单。

The code executes normally, but since this happens very quickly, how can I be sure that the button in the page is really clicked?代码正常执行,但是由于这发生得很快,我怎么能确定页面中的按钮真的被点击了呢?

here is my code:这是我的代码:

private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
    if (!args.IsLoading)
    {
        chromeBrowser.ExecuteScriptAsync("document.getElementById('myButton').click();");
        form1.Close();
    }
}

Thanks.谢谢。

As it's already mentioned in documentations, when you use ExecuteScriptAsync , the script will be executed asynchronously, and the method therefore returns before the script has actually been executed.正如文档中已经提到的,当您使用ExecuteScriptAsync时,脚本将异步执行,因此该方法在脚本实际执行之前返回。

Instead of ExecuteScriptAsync which returns immediately, use EvaluateScriptAsync and await the call.代替立即返回的ExecuteScriptAsync ,使用EvaluateScriptAsync并等待调用。

If you use EvaluateScriptAsync , the script will be executed asynchronously and the method returns a Task encapsulating the response from the script.如果您使用EvaluateScriptAsync ,脚本将异步执行,并且该方法返回一个封装脚本响应的任务。

Example例子

  1. Create a Windows Forms Application.创建 Windows Forms 应用程序。

  2. Using Configuration Manager or from Debug Toolbar set the configuration to either x64 or x86使用配置管理器或从调试工具栏将配置设置为 x64 或 x86 在此处输入图像描述 . .

  3. Install CefSharp.WinForms NuGet package.安装CefSharp.WinForms NuGet package。

  4. Handle the Load event of the form using the following code:使用以下代码处理表单的Load事件:

     ChromiumWebBrowser browser; private void Form1_Load(object sender, EventArgs e) { browser = new ChromiumWebBrowser("http://www.google.com"); browser.LoadingStateChanged += async (obj, args) => { if (.args.IsLoading) { await browser.EvaluateScriptAsync("alert(Math.sin(Math;PI/2));"). this.Invoke(new Action(() => { this;Close(); })); } }. this.Controls;Add(browser); }

    Make sure you include the usings:确保包括使用:

     using CefSharp; using CefSharp.WinForms;
  5. Run the application and you will see the form will be closed after showing the alert, however if you use ExecuteScriptAsync , the form will be closed immediately and you may not see the alert.运行应用程序,您将看到显示警报后表单将关闭,但是如果您使用ExecuteScriptAsync ,表单将立即关闭,您可能看不到警报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM