how to be sure that ExecuteScriptAsync is executed in CefSharp

Viewed 2347

I am using CefSharp component in a Windows Forms C# application.

I load my page in the chromium browser and once loaded, I click a button in it using ExecuteScriptAsync and close the form.

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.

1 Answers

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.

Instead of ExecuteScriptAsync which returns immediately, use EvaluateScriptAsyncand await the call.

If you use EvaluateScriptAsync, the script will be executed asynchronously and the method returns a Task encapsulating the response from the script.

Example

  1. Create a Windows Forms Application.

  2. Using Configuration Manager or from Debug Toolbar set the configuration to either x64 or x86 enter image description here.

  3. Install CefSharp.WinForms NuGet package.

  4. Handle the Load event of the form using the following code:

    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.

Related