CefSharp访问和操纵页面上的内容,可以以编程方式执行 JavaScript 并将其嵌入到页面中,并在触发JavaScript事件时接收回调。您可以使用CefSharp显示使用HTML5构建的嵌入式UI,或显示远程Web内容和Web应用程序。Google Chrome浏览器可以使用很多命令行(CommandLine)配置,有些更改功能的行为,而另一些则用于调试或试验。本文主要介绍.NET(C#)中, 使用CefSharp请求处理页面时设置和读取cookie的方法,以及实现的示例代码。

1、设置cookie

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

2、读取cookie

1) 创建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;
}
}

2) 在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 + "$";  
}  

相关文档:

https://github.com/cefsharp/CefSharp/wiki/Quick-Start

.Net(C#) cefsharp Chrome 浏览器控件后台执行Iframe中的Js代码的方法

.NET(C#) cefsharp 设置浏览器默认语言和userAgent及示例代码

.NET(C#) CefSharp CommandLine开关参数配置和读取网页源代码方法及示例代码

.NET(C#) CefSharp 下载获取页面中指定的文件图片视频等内容(.jpg、.js等)