ChromiumFX - 如何同步获取HTML源代码
本文关键字:获取 HTML 源代码 同步 何同步 ChromiumFX | 更新日期: 2023-09-27 18:31:01
我想从非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 源代码?
我发现。这是我的解决方案。
基于 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();
}