Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EvaluateScriptAsync hanging

In CefSharp WinForms, I'm trying to get the html source of the page using JS once the page has loaded, however the application is freezing. I'm using a BackgroundWorker and the concerned functions are as follows:

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    browser.Load("http://www.google.com");

    browser.FrameLoadEnd += delegate
    {
        object js = EvaluateScript(browser, "1+1");
        MessageBox.Show(js.ToString());
    };
}

object EvaluateScript(ChromiumWebBrowser b, string script)
{
    var task = b.EvaluateScriptAsync(script);
    task.Wait();
    return task.Result;
}
like image 930
Edge Avatar asked May 31 '26 19:05

Edge


2 Answers

As amaitland pointed out, FrameLoadEnd was causing the hang by running in the UI thread. The below code is working:

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    first.Load("http://www.google.com");

    browser.FrameLoadEnd += delegate
    {
        Task task = new Task(() => {
            object js = EvaluateScript(browser, "document.getElementsByTagName('html')[0].innerHTML;");
            MessageBox.Show(js.ToString());
        });
        task.Start();
    };
}

static object EvaluateScript(ChromiumWebBrowser b, string script)
{
    var task = b.EvaluateScriptAsync(script);
    task.Wait();
    JavascriptResponse response = task.Result;
    return response.Success ? (response.Result ?? "") : response.Message;
}
like image 65
Edge Avatar answered Jun 02 '26 07:06

Edge


Whilst you assign FrameLoadEnd in the BackgroundWorker thread, it's actually executed on the underlying CEF UI thread, for which you cannot block without issues.

I'd typically suggest you spawn a Task from within the event handler to complete your work.

like image 44
amaitland Avatar answered Jun 02 '26 09:06

amaitland