CefSharp使用教程三(Cookie处理)

时间:2023-02-08 16:57:00

设置cookie

var cookieManager = CefSharp.Cef.GetGlobalCookieManager(); 
await cookieManager.SetCookieAsync("http://" + domain, new CefSharp.Cookie(
{
Domain = domain,
Name = name,
Value = value,
Expires = DateTime.MinValue
});

读取cookie
建立Cookie读取对象,继承接口 ICookieVisitor

 public class CookieVisitor : CefSharp.ICookieVisitor  
{
public event Action<CefSharp.Cookie> SendCookie;
public bool Visit(CefSharp.Cookie cookie, int count, int total, ref bool deleteCookie)
{
deleteCookie = false;
if (SendCookie != null)
{
SendCookie(cookie);
}

return true;
}
}
/// 回调事件
private void visitor_SendCookie(CefSharp.Cookie obj)
{
cookies += obj.Domain.TrimStart('.') + "^" + obj.Name + "^" + obj.Value + "$";
}

加载指定页面的cookie信息

 /// <summary>
/// html页面加载完成
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
async void webBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
string _url = e.Url;
//判断是否是需要获取cookie的页面
if(_url.Contains("你页面的url连接地址")){
//注册获取cookie回调事件
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += visitor_SycmCookie;
}
}