[Solved] c# Cefsharp how to make correct sequence of JavaScript actions on the web site


As your JavaScript causes a navigation you need to wait for the new page to load.

You can use something like the following to wait for the page load.

// create a static class for the extension method 
public static Task<LoadUrlAsyncResponse> WaitForLoadAsync(this IWebBrowser browser)
{
    var tcs = new TaskCompletionSource<LoadUrlAsyncResponse>(TaskCreationOptions.RunContinuationsAsynchronously);

    EventHandler<LoadErrorEventArgs> loadErrorHandler = null;
    EventHandler<LoadingStateChangedEventArgs> loadingStateChangeHandler = null;

    loadErrorHandler = (sender, args) =>
    {
        //Actions that trigger a download will raise an aborted error.
        //Generally speaking Aborted is safe to ignore
        if (args.ErrorCode == CefErrorCode.Aborted)
        {
            return;
        }

        //If LoadError was called then we'll remove both our handlers
        //as we won't need to capture LoadingStateChanged, we know there
        //was an error
        browser.LoadError -= loadErrorHandler;
        browser.LoadingStateChanged -= loadingStateChangeHandler;

        tcs.TrySetResult(new LoadUrlAsyncResponse(args.ErrorCode, -1));
    };

    loadingStateChangeHandler = (sender, args) =>
    {
        //Wait for while page to finish loading not just the first frame
        if (!args.IsLoading)
        {
            browser.LoadError -= loadErrorHandler;
            browser.LoadingStateChanged -= loadingStateChangeHandler;
            var host = args.Browser.GetHost();

            var navEntry = host?.GetVisibleNavigationEntry();

            int statusCode = navEntry?.HttpStatusCode ?? -1;

            //By default 0 is some sort of error, we map that to -1
            //so that it's clearer that something failed.
            if (statusCode == 0)
            {
                statusCode = -1;
            }

            tcs.TrySetResult(new LoadUrlAsyncResponse(statusCode == -1 ? CefErrorCode.Failed : CefErrorCode.None, statusCode));
        }
    };

    browser.LoadingStateChanged += loadingStateChangeHandler;
    browser.LoadError += loadErrorHandler;

    return tcs.Task;
}

// usage example 
private async void ButtonFind_Click(object sender, EventArgs e)
{

    //Action1
    string jsScript1 = "document.getElementById('story').value=" + '\'' + textFind.Text + '\'';
    await chrome.EvaluateScriptAsync(jsScript1);

    //Action2
    string jsScript2 = "document.querySelector('body > div.wrapper > div.header > div.header44 > div.search_panel > span > form > button').click();";
   
    await Task.WhenAll(chrome.WaitForLoadAsync(), 
      chrome.EvaluateScriptAsync(jsScript2));

    //Action3
    string jsScript3 = "document.getElementsByTagName('a')[2].click();";
    await Task.WhenAll(chrome.WaitForLoadAsync(), 
      chrome.EvaluateScriptAsync(jsScript3));


    //Action4
    string jsScript4 = "document.querySelector('#dle-content > div.section > ul > li:nth-child(3)').click();";
    await chrome.EvaluateScriptAsync(jsScript4);
}

1

solved c# Cefsharp how to make correct sequence of JavaScript actions on the web site