CefSharp 读取Cookie 是通过实现ICookieVisitor接口实现的,代码来自大神jankurianski
如下是 CefSharp3的 WinForms 示例,示例将等待所有Cookie收集完毕后再弹出消息框。修改一下应该就可以直接用到WPF了。:
private void ViewAllCookiesToolStripMenuItem_Click(object sender, EventArgs e)
{
var visitor = new CookieMonster(all_cookies => {
var sb = new StringBuilder();
foreach (var nameValue in all_cookies)
sb.AppendLine(nameValue.Item1 + " = " + nameValue.Item2);
BeginInvoke(new MethodInvoker(() => {
MessageBox.Show(sb.ToString());
}));
});
Cef.VisitAllCookies(visitor);
}
class CookieMonster : ICookieVisitor
{
readonly List<Tuple<string, string>> cookies = new List<Tuple<string, string>>();
readonly Action<IEnumerable<Tuple<string, string>>> useAllCookies;
public CookieMonster(Action<IEnumerable<Tuple<string, string>>> useAllCookies)
{
this.useAllCookies = useAllCookies;
}
public bool Visit(Cookie cookie, int count, int total, ref bool deleteCookie)
{
cookies.Add(new Tuple<string, string>(cookie.Name, cookie.Value));
if (count == total - 1)
useAllCookies(cookies);
return true;
}
}
下面是另一个版本,不过并不是异步工作的,将会冻结主线程,直到Cookie获取完毕。:
private void ViewAllCookiesToolStripMenuItem_Click(object sender, EventArgs e)
{
var visitor = new CookieMonster();
if (Cef.VisitAllCookies(visitor))
visitor.WaitForAllCookies();
var sb = new StringBuilder();
foreach (var nameValue in visitor.NamesValues)
sb.AppendLine(nameValue.Item1 + " = " + nameValue.Item2);
MessageBox.Show(sb.ToString());
}
class CookieMonster : ICookieVisitor
{
readonly List<Tuple<string, string>> cookies = new List<Tuple<string, string>>();
readonly ManualResetEvent gotAllCookies = new ManualResetEvent(false);
public bool Visit(Cookie cookie, int count, int total, ref bool deleteCookie)
{
cookies.Add(new Tuple<string, string>(cookie.Name, cookie.Value));
if (count == total - 1)
gotAllCookies.Set();
return true;
}
public void WaitForAllCookies()
{
gotAllCookies.WaitOne();
}
public IEnumerable<Tuple<string, string>> NamesValues
{
get { return cookies; }
}
}
通过以上方式就可以读取到Cef的Cookie