using CefSharp; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace CsharpHttpHelper { public static class BrowserExtend { 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; } } /// /// 初始化Cef /// /// public static void InitializeCef(string path) { var libraryLoader = new CefSharp.CefLibraryHandle(path + "\\libcef.dll"); var isValid = !libraryLoader.IsInvalid; if (isValid) { _InitializeCef(path);//初始化CEF } else throw new Exception("libcef.dll 加载失败!"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void _InitializeCef(string path) { var browser = path + "\\CefSharp.BrowserSubprocess.exe"; var locales = path + "\\locales"; var settings = new CefSharp.CefSettings { PersistSessionCookies = true, CachePath = path+"\\cache", BrowserSubprocessPath = browser, LocalesDirPath = locales, ResourcesDirPath = path }; CefSharp.Cef.Initialize(settings, false, false); } /// /// 执行JS代码 /// /// 浏览器 /// 执行代码 /// 等待响应结果 /// public static string ExcuteJs(this CefSharp.WinForms.ChromiumWebBrowser browser, string jsCode,bool waitResult = false) { if (waitResult) { Task t = browser.EvaluateScriptAsync(jsCode); t.Wait(); if (t.Result.Result != null) { return t.Result.Result.ToString(); } }else browser.EvaluateScriptAsync(jsCode); return string.Empty; } const string Code_GetElementByClassName = @"function getElementByClassName(className){var aResult =[];var aEle = document.getElementsByTagName('*');for (var i = 0; i < aEle.length; i++){if (aEle[i].className == className){aResult.push(aEle[i]);}}return aResult;}"; /// /// 设置样式 /// public static void SetStyleByClassName(this CefSharp.WinForms.ChromiumWebBrowser browser,string style, string[] classNames) { style = style.Replace("\"","'"); StringBuilder js = new StringBuilder(Code_GetElementByClassName); for (int i = 0; i < classNames.Length; i++) { js.Append("var result = getElementByClassName('" + classNames[i] + "');for(var i=0;i /// 设置样式 /// public static void SetStyleById(this CefSharp.WinForms.ChromiumWebBrowser browser, string style,string[] ids) { style = style.Replace("\"", "'"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ids.Length; i++) { sb.Append("var result =document.getElementById('" + ids[i] + "'); if(typeof(result)=='object'){result.setAttribute('style','" + style + "')}"); } browser.ExcuteJs(sb.ToString(), false); } } }