0

I want to get source of web page in CEF3/Xilium CefGlue rom non-UI thread (offscreen browser)

I do this

internal class TestCefLoadHandler : CefLoadHandler
{
    protected override void OnLoadStart(CefBrowser browser, CefFrame frame)
    {
        // A single CefBrowser instance can handle multiple requests for a single URL if there are frames (i.e. <FRAME>, <IFRAME>).
        if (frame.IsMain)
        {
            Console.WriteLine("START: {0}", browser.GetMainFrame().Url);
        }
    }

    protected override void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
    {
        if (frame.IsMain)
        {
            MyCefStringVisitor mcsv = new MyCefStringVisitor();
            frame.GetSource(mcsv);

            Console.WriteLine("END: {0}, {1}", browser.GetMainFrame().Url, httpStatusCode);
        }
    }
}

class MyCefStringVisitor : CefStringVisitor
{
    private string html;

    protected override void Visit(string value)
    {
        html = value;
    }
    public string Html
    {
        get { return html; }
        set { html = value; }
    }
}

But the call to the

GetSource(...)
is asynchronous, so I need to wait for the call to occur before trying to do anything with result.

How can I wait for the call to occur?

LeMoussel
  • 5,290
  • 12
  • 69
  • 122

1 Answers1

2

According to Alex Maitland tip that said to me that I can be able to adapt the CefSharp implementation (https://github.com/cefsharp/CefSharp/blob/master/CefSharp/TaskStringVisitor.cs) to do something similar.

I do this :

    protected override async void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
    {
        if (frame.IsMain)
        {
            // MAIN CALL TAKES PLACE HERE
            string HTMLsource = await browser.GetSourceAsync();
            Console.WriteLine("END: {0}, {1}", browser.GetMainFrame().Url, httpStatusCode);
        }
    }


public class TaskStringVisitor : CefStringVisitor
{
    private readonly TaskCompletionSource<string> taskCompletionSource;

    public TaskStringVisitor()
    {
        taskCompletionSource = new TaskCompletionSource<string>();
    }

    protected override void Visit(string value)
    {
        taskCompletionSource.SetResult(value);
    }

    public Task<string> Task
    {
        get { return taskCompletionSource.Task; }
    }
}

public static class CEFExtensions
{
    public static Task<string> GetSourceAsync(this CefBrowser browser)
    {
        TaskStringVisitor taskStringVisitor = new TaskStringVisitor();
        browser.GetMainFrame().GetSource(taskStringVisitor);
        return taskStringVisitor.Task;
    }
}  
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
LeMoussel
  • 5,290
  • 12
  • 69
  • 122
  • What do you do with `HTMLSource`? Is there a way to break it out of that callback method so that you can use it? Maybe assign it to a public property? – Robert Harvey Apr 27 '16 at 04:33