CefSharp 获取网页的Cookie可以存入服务器,方便用户下次使用,下次使用Cookie就需要设置CefSharp的Cookie,这里介绍获取Cookie和设置Cookie的 方法:
4.1 设置cookie
var cookieManager = CefSharp.Cef.GetGlobalCookieManager(); await cookieManager.SetCookieAsync("http://" + domain, new CefSharp.Cookie( { Domain = domain, Name = name, Value = value, Expires = DateTime.MinValue });
4.2 读取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; } }
在browser事件中进行处理
private void browser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e) { var cookieManager = CefSharp.Cef.GetGlobalCookieManager(); CookieVisitor visitor = new CookieVisitor(); visitor.SendCookie += visitor_SendCookie; cookieManager.VisitAllCookies(visitor); }
/// 回调事件
private void visitor_SendCookie(CefSharp.Cookie obj) { cookies += obj.Domain.TrimStart('.') + "^" + obj.Name + "^" + obj.Value + "$"; }
之前也有关于CefSharp Cookie的介绍,可以参考:
CefSharp ICookieVisitor 读取Cookie的实现方法
CefSharp ChromiumWebBrowser设置Cookie的方式