ChromiumFX - 如何同步获取HTML源代码?

时间:2016-01-19 10:21:27

标签: c# .net chromium-embedded

我想从非UI线程(屏幕外浏览器)获取CEF3 / ChromiumFX中的网页源

我这样做

void loadHandler_OnLoadEnd(object sender, Chromium.Event.CfxOnLoadEndEventArgs e)
{
    // Get HTML code
    string htmlSource;

    CfxStringVisitor sv = new CfxStringVisitor();
    sv.Visit += ((se, ee) => { htmlSource = ee.String; });
    browser.MainFrame.GetSource(sv);
}

htmlSource始终为NULL。

如何同步获取HTML源?

1 个答案:

答案 0 :(得分:0)

我找到了。这是我的解决方案。

基于CefSharp TaskStringVisitor实现(https://github.com/cefsharp/CefSharp/blob/master/CefSharp/TaskStringVisitor.cs

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

        public TaskStringVisitor()
        {
            taskCompletionSource = new TaskCompletionSource<string>();
            this.Visit += TaskStringVisitor_Visit;
        }

        void TaskStringVisitor_Visit(object sender, Chromium.Event.CfxStringVisitorVisitEventArgs e)
        {
            try
            {
                taskCompletionSource.SetResult(e.String);
            }
            catch (Exception ex)
            {
                taskCompletionSource.SetException(ex);
            }
        }

        public Task<string> Task
        {
            get { return taskCompletionSource.Task; }
        }
    }
    public Task<string> GetSourceAsync()
    {
        TaskStringVisitor taskStringVisitor = new TaskStringVisitor();
        browser.MainFrame.GetSource(taskStringVisitor);

        return taskStringVisitor.Task;
    }

    async void loadHandler_OnLoadEnd(object sender, Chromium.Event.CfxOnLoadEndEventArgs e)
    {
        // Get HTML code
        string HTMLsource = await GetSourceAsync();
    }