Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - how to be sure that ExecuteScriptAsync is executed in CefSharp

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...