Trying to simulate user inputs in CefSharp3 (OffScreen) using JavaScript

℡╲_俬逩灬. 提交于 2020-01-14 04:48:13

问题


I am trying to simulate the user operation on CefSharp(OffScreen) using JavaScript.

Once I load the page (https://www.w3.org),
I am trying to search in the search bar,
click the search button
open first result

So I have used,

            await browser.EvaluateScriptAsync("document.getElementsByName('q')[0].value = 'CSS';");
            await browser.EvaluateScriptAsync("document.getElementById('search-submit').click();");
            await browser.EvaluateScriptAsync("document.getElementById('r1-0').click();");

But the issue I am facing is, to take screenshot, I have to use Thread.Sleep(x) in between and at the end for the pages to load before doing the next operation or take the screenshot.

Is there anyway to avoid the SLEEP and detect when the loading is done, to do the next operation?

I tried ExecuteScriptAsync also, same issue with that also.


回答1:


You can modify and use the LoadPageAsync() function from the OffScreenExample for this purpose.
Just replace alter the parameters by removing the url as you wont be using it, and remove the if statement using the url.
Then on calling the LoadPageAsync after EvaluateScriptAsync with the corresponding browser object.

The Function will look like this after modification.

public static Task LoadPageAsync(IWebBrowser browser)
{
    var tcs = new TaskCompletionSource<bool>();

    EventHandler<LoadingStateChangedEventArgs> handler = null;
    handler = (sender, args) =>
    {
        if (!args.IsLoading)
        {
            browser.LoadingStateChanged -= handler;
            tcs.TrySetResultAsync(true);
        }
    };

    browser.LoadingStateChanged += handler;
    return tcs.Task;
}

Usage will be like,

await browser.EvaluateScriptAsync("document.getElementsByName('q')[0].value = 'CSS';");
await browser.EvaluateScriptAsync("document.getElementById('search-submit').click();");
await LoadPageAsyncCompleted(browser);
await browser.EvaluateScriptAsync("document.getElementById('r1-0').click();");
await LoadPageAsyncCompleted(browser);


来源:https://stackoverflow.com/questions/45587322/trying-to-simulate-user-inputs-in-cefsharp3-offscreen-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!