Xilium CefGlue-如何同步获取HTML源代码? [英] Xilium CefGlue - How to get HTML source synchonously?
本文介绍了Xilium CefGlue-如何同步获取HTML源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取CEF3 / Xilium CefGlue rom非UI线程(屏幕外浏览器)中的网页来源
I want to get source of web page in CEF3/Xilium CefGlue rom non-UI thread (offscreen browser)
我这样做
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; }
}
}
但调用
GetSource(...)
是异步的,因此在尝试对结果进行任何操作之前,我需要等待调用发生。
is asynchronous, so I need to wait for the call to occur before trying to do anything with result.
如何等待通话发生?
推荐答案
根据亚历克斯·梅特兰(Alex Maitland)的提示,我对我说,我可以适应 CefSharp 实现( https://github.com/cefsharp/CefSharp/blob/master/CefSharp/TaskStringVisitor.cs )来执行类似操作。
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.
我这样做:
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;
}
}
这篇关于Xilium CefGlue-如何同步获取HTML源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文