button名 : button1
textbox名: textBox_cookie
- <html>
- <head>
- <title>page1title>
- head>
- <body>
- this is page 111
- <br><a href="page4.html">to page4a>
- <script language=javascript>
-
- document.cookie="username=Tom&age=22";
-
- script>
- body>
- html>
-
- private void button1_Click(object sender, EventArgs e)
- {
- Task<CefSharp.JavascriptResponse> t = webBrower.EvaluateScriptAsync("document.cookie");
- t.Wait();
- var cookie = t.Result.Result;
-
- }
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- this.Load += Form1_Load;
- }
-
- ChromiumWebBrowser webBrower = null;
- string cookies;
- private void Form1_Load(object sender, EventArgs e)
- {
- //初始化配置
- string path = "";
- webBrower = new ChromiumWebBrowser(path);
- webBrower.Dock = DockStyle.Fill;// 填充方式
- webBrower.FrameLoadEnd += WebBrower_FrameLoadEnd;
- button1.Click += button1_Click;
- this.Controls.Add(webBrower);
- //加载测试页面
- webBrower.Load("http://localhost/page1.html");
-
- //模拟写入cookie(测试页面,也有一个cookie)
- var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
- cookieManager.SetCookieAsync("http://localhost", new CefSharp.Cookie()
- {
- Domain = "localhost",
- Name = "1",
- Value = "2",
- Expires = DateTime.MinValue
- });
- }
-
- //加载完成后,获取cookie
- private void WebBrower_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
- {
- //注册获取cookie回调事件
- ICookieManager cookieManager = webBrower.GetCookieManager();
- 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 + "\r\n";
- }
-
- //cefsharp 获取cookie的方法
- public class CookieVisitor : CefSharp.ICookieVisitor
- {
- public event Action
SendCookie; -
- public void Dispose()
- {
-
- }
- public bool Visit(CefSharp.Cookie cookie, int count, int total, ref bool deleteCookie)
- {
- deleteCookie = false;
- if (SendCookie != null)
- {
- SendCookie(cookie);
- }
-
- return true;
- }
- }
-
- //cookie放到text_cookie上
- private void button1_Click(object sender, EventArgs e)
- {
- this.textBox_cookie.Text = cookies;
-
- }
-
-
- }
PS:如果想在FrameLoadEnd事件中显示
那么代码需要委托,
1 Load增加如下
- public Action GetCookie;
- private void Form1_Load(object sender, EventArgs e)
- {
- //绑定获取cookie的委托
- GetCookie = () =>
- {
- Task
t = webBrower.EvaluateScriptAsync("document.cookie"); - t.Wait();
- var cookie = t.Result.Result;
-
- this.textBox_cookie.Text = cookie.ToString();
- };
- }
2 WFrameLoadEnd增加如下
- private void WebBrower_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
- {
-
- this.BeginInvoke(GetCookie);
- }