public static void Init(bool osr, bool multiThreadedMessageLoop, IBrowserProcessHandler browserProcessHandler) { // Set Google API keys, used for Geolocation requests sans GPS. See http://www.chromium.org/developers/how-tos/api-keys // Environment.SetEnvironmentVariable("GOOGLE_API_KEY", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", ""); //Chromium Command Line args //http://peter.sh/experiments/chromium-command-line-switches/ //NOTE: Not all relevant in relation to `CefSharp`, use for reference purposes only. var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; //The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others. //HTML5 databases such as localStorage will only persist across sessions if a cache path is specified. settings.CachePath = "cache"; //settings.UserAgent = "CefSharp Browser" + Cef.CefSharpVersion; // Example User Agent //settings.CefCommandLineArgs.Add("renderer-process-limit", "1"); //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "1"); //settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC //settings.CefCommandLineArgs.Add("no-proxy-server", "1"); //Don't use a proxy server, always make direct connections. Overrides any other proxy server flags that are passed. //settings.CefCommandLineArgs.Add("debug-plugin-loading", "1"); //Dumps extra logging about plugin loading to the log file. //settings.CefCommandLineArgs.Add("disable-plugins-discovery", "1"); //Disable discovering third-party plugins. Effectively loading only ones shipped with the browser plus third-party ones as specified by --extra-plugin-dir and --load-plugin switches //settings.CefCommandLineArgs.Add("enable-system-flash", "1"); //Automatically discovered and load a system-wide installation of Pepper Flash. //settings.CefCommandLineArgs.Add("allow-running-insecure-content", "1"); //By default, an https page cannot run JavaScript, CSS or plugins from http URLs. This provides an override to get the old insecure behavior. Only available in 47 and above. //settings.CefCommandLineArgs.Add("enable-logging", "1"); //Enable Logging for the Renderer process (will open with a cmd prompt and output debug messages - use in conjunction with setting LogSeverity = LogSeverity.Verbose;) //settings.LogSeverity = LogSeverity.Verbose; // Needed for enable-logging to output messages //settings.CefCommandLineArgs.Add("disable-extensions", "1"); //Extension support can be disabled //settings.CefCommandLineArgs.Add("disable-pdf-extension", "1"); //The PDF extension specifically can be disabled //Load the pepper flash player that comes with Google Chrome - may be possible to load these values from the registry and query the dll for it's version info (Step 2 not strictly required it seems) //settings.CefCommandLineArgs.Add("ppapi-flash-path", @"C:\Program Files (x86)\Google\Chrome\Application\47.0.2526.106\PepperFlash\pepflashplayer.dll"); //Load a specific pepper flash version (Step 1 of 2) //settings.CefCommandLineArgs.Add("ppapi-flash-version", "20.0.0.228"); //Load a specific pepper flash version (Step 2 of 2) //NOTE: For OSR best performance you should run with GPU disabled: // `--disable-gpu --disable-gpu-compositing --enable-begin-frame-scheduling` // (you'll loose WebGL support but gain increased FPS and reduced CPU usage). // http://magpcss.org/ceforum/viewtopic.php?f=6&t=13271#p27075 //https://bitbucket.org/chromiumembedded/cef/commits/e3c1d8632eb43c1c2793d71639f3f5695696a5e8 //NOTE: The following function will set all three params //settings.SetOffScreenRenderingBestPerformanceArgs(); //settings.CefCommandLineArgs.Add("disable-gpu", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1"); //Disable Vsync //Disables the DirectWrite font rendering system on windows. //Possibly useful when experiencing blury fonts. //settings.CefCommandLineArgs.Add("disable-direct-write", "1"); settings.MultiThreadedMessageLoop = multiThreadedMessageLoop; settings.ExternalMessagePump = !multiThreadedMessageLoop; // Off Screen rendering (WPF/Offscreen) if (osr) { settings.WindowlessRenderingEnabled = true; //Disable Direct Composition to test https://github.com/cefsharp/CefSharp/issues/1634 //settings.CefCommandLineArgs.Add("disable-direct-composition", "1"); // DevTools doesn't seem to be working when this is enabled // http://magpcss.org/ceforum/viewtopic.php?f=6&t=14095 //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1"); } var proxy = ProxyConfig.GetProxyInformation(); switch (proxy.AccessType) { case InternetOpenType.Direct: { //Don't use a proxy server, always make direct connections. settings.CefCommandLineArgs.Add("no-proxy-server", "1"); break; } case InternetOpenType.Proxy: { settings.CefCommandLineArgs.Add("proxy-server", proxy.ProxyAddress); break; } case InternetOpenType.PreConfig: { settings.CefCommandLineArgs.Add("proxy-auto-detect", "1"); break; } } settings.FocusedNodeChangedEnabled = true; if (!Cef.Initialize(settings, performDependencyCheck: !DebuggingSubProcess, browserProcessHandler: browserProcessHandler)) { throw new Exception("Unable to Initialize Cef"); } }
private void ExitMenuItemClick(object sender, EventArgs e) { browser.Dispose(); Cef.Shutdown(); Close(); }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Cef.Shutdown(); }
public void Init() { InitializeComponent(); IsManipulationEnabled = true; _host = new WindowsFormsHost(); _host.IsManipulationEnabled = true; Loaded += CefView_Loaded; var settings = new CefSettings { RemoteDebuggingPort = RemoteDebuggingPort, CachePath = CacheEnabled ? CachePath : "", UserAgent = UserAgent, UserDataPath = UserDataPath }; CefSharpSettings.ShutdownOnExit = false; switch (LogLevel) { case 0: settings.LogSeverity = LogSeverity.Default; break; case 1: settings.LogSeverity = LogSeverity.Verbose; break; case 2: settings.LogSeverity = LogSeverity.Info; break; case 3: settings.LogSeverity = LogSeverity.Warning; break; case 4: settings.LogSeverity = LogSeverity.Error; break; case 99: settings.LogSeverity = LogSeverity.Disable; break; default: settings.LogSeverity = LogSeverity.Disable; break; } settings.WindowlessRenderingEnabled = false; settings.BrowserSubprocessPath = BrowserSubprocessPath; foreach (var kvp in CommandLineArgs) { settings.CefCommandLineArgs.Add(kvp.Key, kvp.Value); } Cef.EnableHighDPISupport(); if (Cef.Initialize(settings)) { var browser = CreateNewBrowser(); CurrentBrowser = browser; _host.Child = browser; MainGrid.Children.Add(_host); } }
public void ShutDown() { Cef.Shutdown(); }
public static void Init(CefSettingsBase settings, IBrowserProcessHandler browserProcessHandler) { // Set Google API keys, used for Geolocation requests sans GPS. See http://www.chromium.org/developers/how-tos/api-keys // Environment.SetEnvironmentVariable("GOOGLE_API_KEY", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", ""); // Widevine CDM registration - pass in directory where Widevine CDM binaries and manifest.json are located. // For more information on support for DRM content with Widevine see: https://github.com/cefsharp/CefSharp/issues/1934 //Cef.RegisterWidevineCdm(@".\WidevineCdm"); //Chromium Command Line args //http://peter.sh/experiments/chromium-command-line-switches/ //NOTE: Not all relevant in relation to `CefSharp`, use for reference purposes only. //CEF specific command line args //https://bitbucket.org/chromiumembedded/cef/src/master/libcef/common/cef_switches.cc?fileviewer=file-view-default //**IMPORTANT**: For enabled/disabled command line arguments like disable-gpu specifying a value of "0" like //settings.CefCommandLineArgs.Add("disable-gpu", "0"); will have no effect as the second argument is ignored. //**IMPORTANT**: When using command line arguments the behaviour may change between Chromium versions, if you are experiencing //issues after upgrading to a newer version, you should remove all custom command line arguments and add test them in //isolation to determine if they are causing issues. //The command line arguments shown here are here as a reference only and are not tested to confirm they work with each version settings.RemoteDebuggingPort = 8088; //The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others. //HTML5 databases such as localStorage will only persist across sessions if a cache path is specified. settings.RootCachePath = Path.GetFullPath("cache"); //If non-null then CachePath must be equal to or a child of RootCachePath //We're using a sub folder. // settings.CachePath = Path.GetFullPath("cache\\global"); //settings.UserAgent = "CefSharp Browser" + Cef.CefSharpVersion; // Example User Agent //settings.CefCommandLineArgs.Add("renderer-startup-dialog"); //settings.CefCommandLineArgs.Add("enable-media-stream"); //Enable WebRTC //settings.CefCommandLineArgs.Add("no-proxy-server"); //Don't use a proxy server, always make direct connections. Overrides any other proxy server flags that are passed. //settings.CefCommandLineArgs.Add("debug-plugin-loading"); //Dumps extra logging about plugin loading to the log file. //settings.CefCommandLineArgs.Add("disable-plugins-discovery"); //Disable discovering third-party plugins. Effectively loading only ones shipped with the browser plus third-party ones as specified by --extra-plugin-dir and --load-plugin switches //settings.CefCommandLineArgs.Add("enable-system-flash"); //Automatically discovered and load a system-wide installation of Pepper Flash. //settings.CefCommandLineArgs.Add("allow-running-insecure-content"); //By default, an https page cannot run JavaScript, CSS or plugins from http URLs. This provides an override to get the old insecure behavior. Only available in 47 and above. //https://peter.sh/experiments/chromium-command-line-switches/#disable-site-isolation-trials //settings.CefCommandLineArgs.Add("disable-site-isolation-trials"); //NOTE: Running the Network Service in Process is not something CEF officially supports //It may or may not work for newer versions. //settings.CefCommandLineArgs.Add("enable-features", "CastMediaRouteProvider,NetworkServiceInProcess"); //settings.CefCommandLineArgs.Add("enable-logging"); //Enable Logging for the Renderer process (will open with a cmd prompt and output debug messages - use in conjunction with setting LogSeverity = LogSeverity.Verbose;) //settings.LogSeverity = LogSeverity.Verbose; // Needed for enable-logging to output messages //settings.CefCommandLineArgs.Add("disable-extensions"); //Extension support can be disabled //settings.CefCommandLineArgs.Add("disable-pdf-extension"); //The PDF extension specifically can be disabled //Load the pepper flash player that comes with Google Chrome - may be possible to load these values from the registry and query the dll for it's version info (Step 2 not strictly required it seems) //settings.CefCommandLineArgs.Add("ppapi-flash-path", @"C:\Program Files (x86)\Google\Chrome\Application\47.0.2526.106\PepperFlash\pepflashplayer.dll"); //Load a specific pepper flash version (Step 1 of 2) //settings.CefCommandLineArgs.Add("ppapi-flash-version", "20.0.0.228"); //Load a specific pepper flash version (Step 2 of 2) //Audo play example //settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required"; //NOTE: For OSR best performance you should run with GPU disabled: // `--disable-gpu --disable-gpu-compositing --enable-begin-frame-scheduling` // (you'll loose WebGL support but gain increased FPS and reduced CPU usage). // http://magpcss.org/ceforum/viewtopic.php?f=6&t=13271#p27075 //https://bitbucket.org/chromiumembedded/cef/commits/e3c1d8632eb43c1c2793d71639f3f5695696a5e8 //NOTE: The following function will set all three params //settings.SetOffScreenRenderingBestPerformanceArgs(); //settings.CefCommandLineArgs.Add("disable-gpu"); //settings.CefCommandLineArgs.Add("disable-gpu-compositing"); //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling"); //settings.CefCommandLineArgs.Add("disable-gpu-vsync"); //Disable Vsync // The following options control accessibility state for all frames. // These options only take effect if accessibility state is not set by IBrowserHost.SetAccessibilityState call. // --force-renderer-accessibility enables browser accessibility. // --disable-renderer-accessibility completely disables browser accessibility. //settings.CefCommandLineArgs.Add("force-renderer-accessibility"); //settings.CefCommandLineArgs.Add("disable-renderer-accessibility"); //Enables Uncaught exception handler settings.UncaughtExceptionStackSize = 10; //Disable WebAssembly //settings.JavascriptFlags = "--noexpose_wasm"; // Off Screen rendering (WPF/Offscreen) if (settings.WindowlessRenderingEnabled) { //Disable Direct Composition to test https://github.com/cefsharp/CefSharp/issues/1634 //settings.CefCommandLineArgs.Add("disable-direct-composition"); // DevTools doesn't seem to be working when this is enabled // http://magpcss.org/ceforum/viewtopic.php?f=6&t=14095 //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling"); } var proxy = ProxyConfig.GetProxyInformation(); switch (proxy.AccessType) { case InternetOpenType.Direct: { //Don't use a proxy server, always make direct connections. settings.CefCommandLineArgs.Add("no-proxy-server"); break; } case InternetOpenType.Proxy: { settings.CefCommandLineArgs.Add("proxy-server", proxy.ProxyAddress); break; } case InternetOpenType.PreConfig: { settings.CefCommandLineArgs.Add("proxy-auto-detect"); break; } } //settings.LogSeverity = LogSeverity.Verbose; //Experimental setting see https://bitbucket.org/chromiumembedded/cef/issues/2969/support-chrome-windows-with-cef-callbacks //for details //settings.ChromeRuntime = true; if (DebuggingSubProcess) { var architecture = RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(); #if NETCOREAPP settings.BrowserSubprocessPath = Path.GetFullPath("..\\..\\..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin.netcore\\" + architecture + "\\Debug\\netcoreapp3.1\\CefSharp.BrowserSubprocess.exe"); #else settings.BrowserSubprocessPath = Path.GetFullPath("..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe"); #endif } settings.CookieableSchemesList = "custom"; settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), IsSecure = true, //treated with the same security rules as those applied to "https" URLs }); settings.RegisterScheme(new CefCustomScheme { SchemeName = "https", SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), DomainName = ExampleDomain }); settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeNameTest, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), IsSecure = true //treated with the same security rules as those applied to "https" URLs }); //You can use the http/https schemes - best to register for a specific domain settings.RegisterScheme(new CefCustomScheme { SchemeName = "https", SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), DomainName = "cefsharp.com", IsSecure = true //treated with the same security rules as those applied to "https" URLs }); const string cefSharpExampleResourcesFolder = #if !NETCOREAPP @"..\..\..\..\CefSharp.Example\Resources"; #else @"..\..\..\..\..\..\CefSharp.Example\Resources"; #endif settings.RegisterScheme(new CefCustomScheme { SchemeName = "localfolder", SchemeHandlerFactory = new FolderSchemeHandlerFactory(rootFolder: cefSharpExampleResourcesFolder, schemeName: "localfolder", //Optional param no schemename checking if null hostName: "cefsharp", //Optional param no hostname checking if null defaultPage: "home.html") //Optional param will default to index.html }); //This must be set before Cef.Initialized is called CefSharpSettings.FocusedNodeChangedEnabled = true; //Async Javascript Binding - methods are queued on TaskScheduler.Default. //Set this to true to when you have methods that return Task<T> //CefSharpSettings.ConcurrentTaskExecution = true; //Legacy Binding Behaviour - Same as Javascript Binding in version 57 and below //See issue https://github.com/cefsharp/CefSharp/issues/1203 for details //CefSharpSettings.LegacyJavascriptBindingEnabled = true; //Exit the subprocess if the parent process happens to close //This is optional at the moment //https://github.com/cefsharp/CefSharp/pull/2375/ CefSharpSettings.SubprocessExitIfParentProcessClosed = true; //NOTE: Set this before any calls to Cef.Initialize to specify a proxy with username and password //One set this cannot be changed at runtime. If you need to change the proxy at runtime (dynamically) then //see https://github.com/cefsharp/CefSharp/wiki/General-Usage#proxy-resolution //CefSharpSettings.Proxy = new ProxyOptions(ip: "127.0.0.1", port: "8080", username: "******", password: "******"); bool performDependencyCheck = !DebuggingSubProcess; if (!Cef.Initialize(settings, performDependencyCheck: performDependencyCheck, browserProcessHandler: browserProcessHandler)) { throw new Exception("Unable to Initialize Cef"); } Cef.AddCrossOriginWhitelistEntry(BaseUrl, "https", "cefsharp.com", false); }
/// <summary> /// Clears cookies of the built-in browser component. Note that this clears cookies globally /// for all Cef-based browsers. /// </summary> public static void ClearCookies() { Cef.GetGlobalCookieManager().DeleteCookies("", ""); }
private void RemoveFromListOfCefBrowsers() { Cef.RemoveDisposable(this); }
/// <summary> /// starts up & loads cef instance. /// </summary> public void InitializeChromium() { CefSettings settings = new CefSettings(); if (linkType == LinkType.local) { settings.RegisterScheme(new CefCustomScheme { SchemeName = "localfolder", //DomainName = "html",//Path.GetFileName(path),//"cefsharp", SchemeHandlerFactory = new FolderSchemeHandlerFactory ( rootFolder: Path.GetDirectoryName(path), hostName: Path.GetFileName(path), defaultPage: Path.GetFileName(path) //"index.html" // will default to index.html ) }); path = "localfolder://" + Path.GetFileName(path); } //ref: https://magpcss.org/ceforum/apidocs3/projects/(default)/_cef_browser_settings_t.html#universal_access_from_file_urls //settings.CefCommandLineArgs.Add("allow-universal-access-from-files", "1"); //UNSAFE, Testing Only! settings.CefCommandLineArgs.Add("--mute-audio", "1"); if (linkType == LinkType.deviantart) { //System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "//LivelyCefCache"); settings.CachePath = AppDomain.CurrentDomain.BaseDirectory + "//LivelyCefCache"; } Cef.Initialize(settings); if (linkType == LinkType.shadertoy) { chromeBrowser = new ChromiumWebBrowser(String.Empty); path = ShadertoyURLtoEmbedLink(path); chromeBrowser.LoadHtml(path); } else { chromeBrowser = new ChromiumWebBrowser(path); if (linkType == LinkType.deviantart) { chromeBrowser.DownloadHandler = new DownloadHandler(); } } this.Controls.Add(chromeBrowser); //chromeBrowser.Anchor = AnchorStyles.Top; //chromeBrowser.Location = new Point(0, 0); chromeBrowser.Dock = DockStyle.Fill; //Top: Hide scrollbars? chromeBrowser.IsBrowserInitializedChanged += ChromeBrowser_IsBrowserInitializedChanged1; chromeBrowser.LoadingStateChanged += ChromeBrowser_LoadingStateChanged; chromeBrowser.LoadError += ChromeBrowser_LoadError; /* * //binding test * if (enableCSCore) * { * chromeBrowser.JavascriptObjectRepository.Register("boundAsync", this._lineSpectrum, true); * } */ }
/// <summary> /// 【setup2】提取cookie /// </summary> /// <param name="browserControl"></param> /// <param name="browser"></param> /// <param name="frame"></param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="status"></param> /// <param name="receivedContentLength"></param> public override void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength) { if (response.StatusCode != 200) { return; } var url = new Uri(request.Url); var extension = url.ToString().ToLower(); if (SystemSetting.SystemSettingDict["OpenDebug"] == "true") {//开启debug模式 extension.WriteLog(ELogType.Account, true); //输入写入到请求日志 IPostData data = request.PostData; if (data != null) { //请求内容被转换为了文件流 //输出有请求参数的URL StringBuilder requestHead = new StringBuilder(); requestHead.AppendLine(string.Format("url hava request param-> {0} ", extension)); foreach (var item in request.Headers.AllKeys) { requestHead.Append(string.Format("{0} : {1};", item, request.Headers[item])); } requestHead.ToString().WriteLog(ELogType.HttpRequest, true); } } //if (!extension.Contains(SystemConfig.CookieDomain)) //{ // return; //} if ((!SystemConfig.AnywhereGetCookie && extension != SystemConfig.InitCookeKey)) { return; } //这是请求响应头 ICookieManager cookie = Cef.GetGlobalCookieManager(); if (SystemConfig.AnywhereGetCookie) {//无限制提取cookie cookie.VisitAllCookies(new CookieVisitor()); } else { foreach (var urlFrom in SystemConfig.CookieFrom) { cookie.VisitUrlCookies(urlFrom, false, new CookieVisitor()); } } if (extension == SystemConfig.TockenAfterUrl) {//是否已经获取到了tocken ExistsTocken = true; } if (CookieHandle.GetCoreCookie(CookieVisitor.CookieDict)) { //从其他应用中获取到了cookie ExistsTocken = true; } if (ExistsTocken) {//提取到了完整的cookie StringBuilder cook = new StringBuilder(); cook.AppendLine(CookieVisitor.OutputCookie(CookieVisitor.CookieDict).ToString()); cook.ToString().WriteLog(ELogType.SessionOrCookieLog, true); //CookieContainer GetCookieResponse(CookieVisitor.CookieDict); } if (_requestHeandler != null) { _requestHeandler.OnResourceLoadComplete(browserControl, browser, frame, request, response, status, receivedContentLength); } if (SystemConfig.DownloadResource) { DownloadService.DownloadResource(extension, responseDictionary, request, response); } return; }
private static async void MainAsync(string cachePath, double zoomLevel) { var browserSettings = new BrowserSettings(); //Reduce rendering speed to one frame per second so it's easier to take screen shots browserSettings.WindowlessFrameRate = 1; var requestContextSettings = new RequestContextSettings { CachePath = cachePath }; // RequestContext can be shared between browser instances and allows for custom settings // e.g. CachePath using (var requestContext = new RequestContext(requestContextSettings)) using (var browser = new ChromiumWebBrowser(TestUrl, browserSettings, requestContext)) { if (zoomLevel > 1) { browser.FrameLoadStart += (s, argsi) => { var b = (ChromiumWebBrowser)s; if (argsi.Frame.IsMain) { b.SetZoomLevel(zoomLevel); } }; } await LoadPageAsync(browser); //Check preferences on the CEF UI Thread await Cef.UIThreadTaskFactory.StartNew(delegate { var preferences = requestContext.GetAllPreferences(true); //Check do not track status var doNotTrack = (bool)preferences["enable_do_not_track"]; Debug.WriteLine("DoNotTrack:" + doNotTrack); }); var onUi = Cef.CurrentlyOnThread(CefThreadIds.TID_UI); // For Google.com pre-pupulate the search text box await browser.EvaluateScriptAsync("document.getElementById('lst-ib').value = 'CefSharp Was Here!'"); // Wait for the screenshot to be taken, // if one exists ignore it, wait for a new one to make sure we have the most up to date await browser.ScreenshotAsync(true).ContinueWith(DisplayBitmap); await LoadPageAsync(browser, "http://github.com"); //Gets a wrapper around the underlying CefBrowser instance var cefBrowser = browser.GetBrowser(); // Gets a warpper around the CefBrowserHost instance // You can perform a lot of low level browser operations using this interface var cefHost = cefBrowser.GetHost(); //You can call Invalidate to redraw/refresh the image cefHost.Invalidate(PaintElementType.View); // Wait for the screenshot to be taken. await browser.ScreenshotAsync(true).ContinueWith(DisplayBitmap); } }
public void TestMethod1() { Cef.Initialize(); }
public App() { Cef.Initialize(new CefSettings()); }
public static void Shutdown() { Cef.Shutdown(); }
private void FormTestJsCommunication_FormClosing(object sender, FormClosingEventArgs e) { Cef.Shutdown(); }
public static int Main(string[] args) { if (args.Length == 0) { args = new string[] { //"https://pipeline.mediumra.re", //"https://pipeline.mediumra.re/pages-app.html", "https://pipeline.mediumra.re/nav-side-kanban-board.html", //Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pipeline.mediumra.re") } } ; string URL = args[0]; try { SITE = new oSite(); Uri uri = new Uri(URL); string PATH_STORE = Utility.build_path_folder_save(uri); string file = Utility.build_path_file_save(uri); Console.Title = URL + " -> " + file; SITE.NAME = uri.AbsolutePath.Split('?')[0].Replace('/', '_').Trim().ToLower(); if (SITE.NAME[0] == '_') { SITE.NAME = SITE.NAME.Substring(1); } if (SITE.NAME.Length == 0) { SITE.NAME = "index.html"; } SITE.URL = uri; SITE.PATH_STORE = PATH_STORE; if (File.Exists(file)) { string f_links = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, uri.Host.Replace(':', '_') + ".txt"); if (File.Exists(f_links)) { var lines = File.ReadAllLines(f_links) .Where(o => o.Trim().Length > 0) .Where(o => File.Exists(Utility.build_path_file_save(new Uri(o))) == false) .ToArray(); if (lines.Length > 0) { File.WriteAllLines(f_links, lines.Where((o, i) => i != 0)); return(Main(new string[] { lines[0] })); } else { MessageBox.Show("Download theme: " + uri.Host + " complete"); return(0); } } } if (browser == null) { var settings = new CefSettings() { CachePath = null }; Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null); } else { browser.Stop(); browser.Dispose(); } browser = new ChromiumWebBrowser(URL); browser.Size = new System.Drawing.Size(1366, 3500); browser.LoadingStateChanged += BrowserLoadingStateChanged; browser.RequestHandler = new CefBasicRequestHandler(SITE); signal.WaitOne(); signal.Reset(); if (string.IsNullOrEmpty(URL_NEXT)) { MessageBox.Show("Download theme: " + uri.Host + " complete"); } else { return(Main(new string[] { URL_NEXT })); } Cef.Shutdown(); } catch { Cef.Shutdown(); Process.Start(Application.ExecutablePath, URL); Environment.Exit(0); } return(0); }
public static async void RegisterTestResources(IWebBrowser browser) { if (browser.ResourceRequestHandlerFactory == null) { browser.ResourceRequestHandlerFactory = new ResourceRequestHandlerFactory(); } var handler = browser.ResourceRequestHandlerFactory as ResourceRequestHandlerFactory; if (handler != null) { const string renderProcessCrashedBody = "<html><body><h1>Render Process Crashed</h1><p>Your seeing this message as the render process has crashed</p></body></html>"; handler.RegisterHandler(RenderProcessCrashedUrl, ResourceHandler.GetByteArray(renderProcessCrashedBody, Encoding.UTF8)); const string responseBody = "<html><body><h1>Success</h1><p>This document is loaded from a System.IO.Stream</p></body></html>"; handler.RegisterHandler(TestResourceUrl, ResourceHandler.GetByteArray(responseBody, Encoding.UTF8)); const string unicodeResponseBody = "<html><body>整体满意度</body></html>"; handler.RegisterHandler(TestUnicodeResourceUrl, ResourceHandler.GetByteArray(unicodeResponseBody, Encoding.UTF8)); if (string.IsNullOrEmpty(PluginInformation)) { var pluginBody = new StringBuilder(); pluginBody.Append("<html><body><h1>Plugins</h1><table>"); pluginBody.Append("<tr>"); pluginBody.Append("<th>Name</th>"); pluginBody.Append("<th>Description</th>"); pluginBody.Append("<th>Version</th>"); pluginBody.Append("<th>Path</th>"); pluginBody.Append("</tr>"); var plugins = await Cef.GetPlugins(); if (plugins.Count == 0) { pluginBody.Append("<tr>"); pluginBody.Append("<td colspan='4'>Cef.GetPlugins returned an empty list - likely no plugins were loaded on your system</td>"); pluginBody.Append("</tr>"); pluginBody.Append("<tr>"); pluginBody.Append("<td colspan='4'>You may find that NPAPI/PPAPI need to be enabled</td>"); pluginBody.Append("</tr>"); } else { foreach (var plugin in plugins) { pluginBody.Append("<tr>"); pluginBody.Append("<td>" + plugin.Name + "</td>"); pluginBody.Append("<td>" + plugin.Description + "</td>"); pluginBody.Append("<td>" + plugin.Version + "</td>"); pluginBody.Append("<td>" + plugin.Path + "</td>"); pluginBody.Append("</tr>"); } } pluginBody.Append("</table></body></html>"); PluginInformation = pluginBody.ToString(); } handler.RegisterHandler(PluginsTestUrl, ResourceHandler.GetByteArray(PluginInformation, Encoding.UTF8)); } }
private void Frm_webrowser_FormClosing(object sender, FormClosingEventArgs e) { Cef.Shutdown(); }
public ExploitScreen() { Cef.EnableHighDPISupport(); var settings = new CefSettings(); settings.SetOffScreenRenderingBestPerformanceArgs(); Cef.Initialize(settings); var SLib = Globals.SxLib; SLib.SetWindow(this); SLib.AttachEvent += async(SEvent, Param) => { switch (SEvent) { case SxLibBase.SynAttachEvents.CHECKING: { showStatusLabel(); headerStatusLabel.Content = "Checking..."; break; } case SxLibBase.SynAttachEvents.INJECTING: { headerStatusLabel.Content = "Injecting..."; break; } case SxLibBase.SynAttachEvents.CHECKING_WHITELIST: { headerStatusLabel.Content = "Checking Whitelist..."; break; } case SxLibBase.SynAttachEvents.SCANNING: { showStatusLabel(); headerStatusLabel.Content = "Scanning..."; break; } case SxLibBase.SynAttachEvents.READY: { headerStatusLabel.Content = "Ready!"; attachNotify.Stop(); designMethods.ButtonColor(attachButton, brushConverter.ConvertToString(attachButton.Background), "#FF3C3C3C"); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.ALREADY_INJECTED: { error("Already injected!"); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.FAILED_TO_ATTACH: { error("Failed to attach!"); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.FAILED_TO_FIND: { error("Failed to find Roblox!"); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.NOT_RUNNING_LATEST_VER_UPDATING: { headerStatusLabel.Content = "Not running latest version, updating..."; break; } case SxLibBase.SynAttachEvents.UPDATING_DLLS: { headerStatusLabel.Content = "Updating DLLs..."; break; } case SxLibBase.SynAttachEvents.NOT_UPDATED: { error("Not updated! Please try again in a little while."); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.FAILED_TO_UPDATE: { error("Auto-update failed! Please restart Synapse X."); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.REINJECTING: { headerStatusLabel.Content = "Update complete, reinjecting..."; break; } case SxLibBase.SynAttachEvents.NOT_INJECTED: { error("Not injected!"); await Task.Delay(1000); hideStatusLabel(); break; } case SxLibBase.SynAttachEvents.PROC_CREATION: { attachNotify.Start(); break; } case SxLibBase.SynAttachEvents.PROC_DELETION: { attachNotify.Stop(); designMethods.ButtonColor(attachButton, brushConverter.ConvertToString(attachButton.Background), "#FF3C3C3C"); await Task.Delay(1000); break; } } }; SLib.ScriptHubEvent += Entries => { scriptHubButton.Content = "Script Hub"; ScriptHubScreen scriptHub = new ScriptHubScreen(exploitScreen, Entries); scriptHub.Show(); Focus(); }; InitializeComponent(); Title = Globals.RandomString(Globals.Rnd.Next(10, 32)); designMethods = new InterfaceDesign(); new Random(); brushConverter = new BrushConverter(); openFileDialog = new OpenFileDialog { Title = "Load Script from File", Filter = "Script files|*.lua;*.txt" }; attachNotify = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; attachNotify.Tick += AttachNotify_Tick; if (Process.GetProcessesByName("RobloxPlayerBeta").Length != 0) { attachNotify.Start(); } scriptsDirectory = Path.Combine(Path.Combine(Directory.GetParent(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)).FullName), "scripts"); foreach (var FilePath in Directory.GetFiles(scriptsDirectory)) { synScripts.Items.Add(Path.GetFileName(FilePath)); } }
public BrowserTabView() { InitializeComponent(); DataContextChanged += OnDataContextChanged; //browser.BrowserSettings.BackgroundColor = Cef.ColorSetARGB(0, 255, 255, 255); //Please remove the comments below to use the Experimental WpfImeKeyboardHandler. //browser.WpfKeyboardHandler = new CefSharp.Wpf.Experimental.WpfImeKeyboardHandler(browser); //Please remove the comments below to specify the color of the CompositionUnderline. //var transparent = Colors.Transparent; //var black = Colors.Black; //ImeHandler.ColorBKCOLOR = Cef.ColorSetARGB(transparent.A, transparent.R, transparent.G, transparent.B); //ImeHandler.ColorUNDERLINE = Cef.ColorSetARGB(black.A, black.R, black.G, black.B); browser.RequestHandler = new ExampleRequestHandler(); var bindingOptions = new BindingOptions() { Binder = BindingOptions.DefaultBinder.Binder, MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it }; //To use the ResolveObject below and bind an object with isAsync:false we must set CefSharpSettings.WcfEnabled = true before //the browser is initialized. #if !NETCOREAPP CefSharpSettings.WcfEnabled = true; #endif //If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet //bound, then ResolveObject will be called, you can then register it browser.JavascriptObjectRepository.ResolveObject += (sender, e) => { var repo = e.ObjectRepository; //When JavascriptObjectRepository.Settings.LegacyBindingEnabled = true //This event will be raised with ObjectName == Legacy so you can bind your //legacy objects #if NETCOREAPP if (e.ObjectName == "Legacy") { repo.Register("boundAsync", new AsyncBoundObject(), options: bindingOptions); } else { if (e.ObjectName == "boundAsync") { repo.Register("boundAsync", new AsyncBoundObject(), options: bindingOptions); } else if (e.ObjectName == "boundAsync2") { repo.Register("boundAsync2", new AsyncBoundObject(), options: bindingOptions); } } #else if (e.ObjectName == "Legacy") { repo.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder); repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } else { if (e.ObjectName == "bound") { repo.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder); } else if (e.ObjectName == "boundAsync") { repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } else if (e.ObjectName == "boundAsync2") { repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } } #endif }; browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) => { var name = e.ObjectName; Debug.WriteLine($"Object {e.ObjectName} was bound successfully."); }; browser.DisplayHandler = new DisplayHandler(); //This LifeSpanHandler implementaion demos hosting a popup in a ChromiumWebBrowser //instance, it's still considered Experimental //browser.LifeSpanHandler = new ExperimentalLifespanHandler(); browser.MenuHandler = new MenuHandler(addDevtoolsMenuItems: true); //Enable experimental Accessibility support browser.AccessibilityHandler = new AccessibilityHandler(browser); browser.IsBrowserInitializedChanged += (sender, args) => { if ((bool)args.NewValue) { //Uncomment to enable support //browser.GetBrowserHost().SetAccessibilityState(CefState.Enabled); } }; var downloadHandler = new DownloadHandler(); downloadHandler.OnBeforeDownloadFired += OnBeforeDownloadFired; downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired; browser.DownloadHandler = downloadHandler; browser.AudioHandler = new CefSharp.Handler.AudioHandler(); //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg var beachImageStream = new MemoryStream(); CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, Cef.GetMimeType("jpg")); var dragHandler = new DragHandler(); dragHandler.RegionsChanged += OnDragHandlerRegionsChanged; browser.DragHandler = dragHandler; //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory(); //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler //browser.RequestContext = new RequestContext(new RequestContextHandler()); //NOTE - This is very important for this example as the default page will not load otherwise //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory()); //browser.RequestContext.RegisterSchemeHandlerFactory("https", "cefsharp.example", new CefSharpSchemeHandlerFactory()); //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread. //Cef.UIThreadTaskFactory.StartNew(delegate //{ // string errorMessage; // //Use this to check that settings preferences are working in your code // var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage); //}); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); browser.LoadError += (sender, args) => { // Don't display an error for downloaded files. if (args.ErrorCode == CefErrorCode.Aborted) { return; } //Don't display an error for external protocols that we allow the OS to //handle in OnProtocolExecution(). if (args.ErrorCode == CefErrorCode.UnknownUrlScheme && args.Frame.Url.StartsWith("mailto")) { return; } // Display a load error message. var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>", args.FailedUrl, args.ErrorText, args.ErrorCode); args.Frame.LoadHtml(errorBody, base64Encode: true); }; CefExample.RegisterTestResources(browser); browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived; }
protected override void OnExit(ExitEventArgs e) { Cef.Shutdown(); Application.Current.Shutdown(); base.OnExit(e); }
public void ClearData() { Cef.GetGlobalCookieManager().DeleteCookies(); }
public static void Init(bool osr, bool multiThreadedMessageLoop) { // Set Google API keys, used for Geolocation requests sans GPS. See http://www.chromium.org/developers/how-tos/api-keys // Environment.SetEnvironmentVariable("GOOGLE_API_KEY", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", ""); //Chromium Command Line args //http://peter.sh/experiments/chromium-command-line-switches/ //NOTE: Not all relevant in relation to `CefSharp`, use for reference purposes only. var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; //The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others. //HTML5 databases such as localStorage will only persist across sessions if a cache path is specified. settings.CachePath = "cache"; //settings.UserAgent = "CefSharp Browser" + Cef.CefSharpVersion; // Example User Agent //settings.CefCommandLineArgs.Add("renderer-process-limit", "1"); //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "1"); //settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC //settings.CefCommandLineArgs.Add("no-proxy-server", "1"); //Don't use a proxy server, always make direct connections. Overrides any other proxy server flags that are passed. //settings.CefCommandLineArgs.Add("debug-plugin-loading", "1"); //Dumps extra logging about plugin loading to the log file. //settings.CefCommandLineArgs.Add("disable-plugins-discovery", "1"); //Disable discovering third-party plugins. Effectively loading only ones shipped with the browser plus third-party ones as specified by --extra-plugin-dir and --load-plugin switches //settings.CefCommandLineArgs.Add("enable-system-flash", "1"); //Automatically discovered and load a system-wide installation of Pepper Flash. //settings.CefCommandLineArgs.Add("allow-running-insecure-content", "1"); //By default, an https page cannot run JavaScript, CSS or plugins from http URLs. This provides an override to get the old insecure behavior. Only available in 47 and above. //settings.CefCommandLineArgs.Add("enable-logging", "1"); //Enable Logging for the Renderer process (will open with a cmd prompt and output debug messages - use in conjunction with setting LogSeverity = LogSeverity.Verbose;) //settings.LogSeverity = LogSeverity.Verbose; // Needed for enable-logging to output messages //settings.CefCommandLineArgs.Add("disable-extensions", "1"); //Extension support can be disabled //settings.CefCommandLineArgs.Add("disable-pdf-extension", "1"); //The PDF extension specifically can be disabled //Load the pepper flash player that comes with Google Chrome - may be possible to load these values from the registry and query the dll for it's version info (Step 2 not strictly required it seems) //settings.CefCommandLineArgs.Add("ppapi-flash-path", @"C:\Program Files (x86)\Google\Chrome\Application\47.0.2526.106\PepperFlash\pepflashplayer.dll"); //Load a specific pepper flash version (Step 1 of 2) //settings.CefCommandLineArgs.Add("ppapi-flash-version", "20.0.0.228"); //Load a specific pepper flash version (Step 2 of 2) //NOTE: For OSR best performance you should run with GPU disabled: // `--disable-gpu --disable-gpu-compositing --enable-begin-frame-scheduling` // (you'll loose WebGL support but gain increased FPS and reduced CPU usage). // http://magpcss.org/ceforum/viewtopic.php?f=6&t=13271#p27075 //https://bitbucket.org/chromiumembedded/cef/commits/e3c1d8632eb43c1c2793d71639f3f5695696a5e8 //NOTE: The following function will set all three params //settings.SetOffScreenRenderingBestPerformanceArgs(); //settings.CefCommandLineArgs.Add("disable-gpu", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1"); //Disable Vsync //Disables the DirectWrite font rendering system on windows. //Possibly useful when experiencing blury fonts. //settings.CefCommandLineArgs.Add("disable-direct-write", "1"); settings.MultiThreadedMessageLoop = multiThreadedMessageLoop; // Off Screen rendering (WPF/Offscreen) if (osr) { settings.WindowlessRenderingEnabled = true; // Disable Surfaces so internal PDF viewer works for OSR // https://bitbucket.org/chromiumembedded/cef/issues/1689 //settings.CefCommandLineArgs.Add("disable-surfaces", "1"); settings.EnableInternalPdfViewerOffScreen(); var osVersion = Environment.OSVersion; //Disable GPU for Windows 7 if (osVersion.Version.Major == 6 && osVersion.Version.Minor == 1) { // Disable GPU in WPF and Offscreen examples until #1634 has been resolved settings.CefCommandLineArgs.Add("disable-gpu", "1"); } // DevTools doesn't seem to be working when this is enabled // http://magpcss.org/ceforum/viewtopic.php?f=6&t=14095 //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1"); } var proxy = ProxyConfig.GetProxyInformation(); switch (proxy.AccessType) { case InternetOpenType.Direct: { //Don't use a proxy server, always make direct connections. settings.CefCommandLineArgs.Add("no-proxy-server", "1"); break; } case InternetOpenType.Proxy: { settings.CefCommandLineArgs.Add("proxy-server", proxy.ProxyAddress); break; } case InternetOpenType.PreConfig: { settings.CefCommandLineArgs.Add("proxy-auto-detect", "1"); break; } } //settings.LogSeverity = LogSeverity.Verbose; if (DebuggingSubProcess) { var architecture = Environment.Is64BitProcess ? "x64" : "x86"; settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() //SchemeHandlerFactory = new InMemorySchemeAndResourceHandlerFactory() }); settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeNameTest, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); settings.RegisterScheme(new CefCustomScheme { SchemeName = "localfolder", SchemeHandlerFactory = new FolderSchemeHandlerFactory(rootFolder: @"..\..\..\..\CefSharp.Example\Resources", schemeName: "localfolder", //Optional param no schemename checking if null hostName: "cefsharp", //Optional param no hostname checking if null defaultPage: "home.html") //Optional param will default to index.html }); settings.RegisterExtension(new CefExtension("cefsharp/example", Resources.extension)); settings.FocusedNodeChangedEnabled = true; //The Request Context has been initialized, you can now set preferences, like proxy server settings Cef.OnContextInitialized = delegate { var cookieManager = Cef.GetGlobalCookieManager(); cookieManager.SetStoragePath("cookies", true); cookieManager.SetSupportedSchemes("custom"); //Dispose of context when finished - preferable not to keep a reference if possible. using (var context = Cef.GetGlobalRequestContext()) { string errorMessage; //You can set most preferences using a `.` notation rather than having to create a complex set of dictionaries. //The default is true, you can change to false to disable context.SetPreference("webkit.webprefs.plugins_enabled", true, out errorMessage); } }; if (!Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: !DebuggingSubProcess)) { throw new Exception("Unable to Initialize Cef"); } }
public static int Main(string[] args) { const bool simpleSubProcess = false; Cef.EnableHighDPISupport(); //NOTE: Using a simple sub processes uses your existing application executable to spawn instances of the sub process. //Features like JSB, EvaluateScriptAsync, custom schemes require the CefSharp.BrowserSubprocess to function if (simpleSubProcess) { var exitCode = Cef.ExecuteProcess(); if (exitCode >= 0) { return(exitCode); } #if DEBUG if (!System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("When running this Example outside of Visual Studio" + "please make sure you compile in `Release` mode.", "Warning"); } #endif var settings = new CefSettings(); settings.BrowserSubprocessPath = "CefSharp.WinForms.Example.exe"; Cef.Initialize(settings); var browser = new SimpleBrowserForm(); Application.Run(browser); } else { #if DEBUG if (!System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("When running this Example outside of Visual Studio" + "please make sure you compile in `Release` mode.", "Warning"); } #endif const bool multiThreadedMessageLoop = true; var browser = new BrowserForm(multiThreadedMessageLoop); //var browser = new SimpleBrowserForm(); //var browser = new TabulationDemoForm(); IBrowserProcessHandler browserProcessHandler; if (multiThreadedMessageLoop) { browserProcessHandler = new BrowserProcessHandler(); } else { //Get the current taskScheduler (must be called after the form is created) var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); browserProcessHandler = new WinFormsBrowserProcessHandler(scheduler); } var settings = new CefSettings(); settings.MultiThreadedMessageLoop = multiThreadedMessageLoop; settings.ExternalMessagePump = !multiThreadedMessageLoop; CefExample.Init(settings, browserProcessHandler: browserProcessHandler); Application.Run(browser); } return(0); }
public void Shutdown() { try { Cef.Shutdown(); } catch { } }
internal void Exit() { Cef.Shutdown(); }
public void Start() { //For Windows 7 and above, best to include relevant app.manifest entries as well Cef.EnableHighDPISupport(); var cefsettings = new CefSettings() { Locale = "zh-CN", //By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data CachePath = Path.Combine(Environment.CurrentDirectory, "cache"), IgnoreCertificateErrors = true, LogSeverity = LogSeverity.Disable, }; cefsettings.CefCommandLineArgs.Add("disable-gpu", "1"); cefsettings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); //Perform dependency check to make sure all relevant resources are in our output directory. Cef.Initialize(cefsettings, performDependencyCheck: true, browserProcessHandler: null); var path = new FileInfo(Process.GetCurrentProcess().MainModule.FileName).DirectoryName; var resource = Path.Combine(path, "resource"); var webuis = Directory.GetDirectories(resource); if (webuis.Length == 0) { MessageBox.Show("缺少WebUI资源"); Application.Exit(); } var portHelper = new PortHelper(); var aria2c = new Aria2c(); if (portHelper.GetUsedPorts().Contains(6800)) { var choice = MessageBox.Show( "检测到6800端口已被占用,请检查是否为aria2c程序。\r\n\r\n" + "若为aria2c,是否关闭已开启的aria2c,并开启新的例程?\r\n\r\n" + "选择“是”开启新的例程,选择“否”继续使用已开启的例程,选择“取消”退出程序" , "提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (choice == DialogResult.Yes) { aria2c.Stop(); aria2c.Start(); } else if (choice == DialogResult.No) { } else { Environment.Exit(0); return; } } else { aria2c.Start(); } var port = portHelper.GetRandPort(); var server = new InternalWebServer(resource, port); server.Start(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm(aria2c, server)); }
public static void Init(AbstractCefSettings settings, IBrowserProcessHandler browserProcessHandler) { // Set Google API keys, used for Geolocation requests sans GPS. See http://www.chromium.org/developers/how-tos/api-keys // Environment.SetEnvironmentVariable("GOOGLE_API_KEY", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", ""); // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", ""); // Widevine CDM registration - pass in directory where Widevine CDM binaries and manifest.json are located. // For more information on support for DRM content with Widevine see: https://github.com/cefsharp/CefSharp/issues/1934 //Cef.RegisterWidevineCdm(@".\WidevineCdm"); //Chromium Command Line args //http://peter.sh/experiments/chromium-command-line-switches/ //NOTE: Not all relevant in relation to `CefSharp`, use for reference purposes only. settings.RemoteDebuggingPort = 8088; //The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others. //HTML5 databases such as localStorage will only persist across sessions if a cache path is specified. settings.CachePath = "cache"; //settings.UserAgent = "CefSharp Browser" + Cef.CefSharpVersion; // Example User Agent //settings.CefCommandLineArgs.Add("renderer-process-limit", "1"); //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "1"); //settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC //settings.CefCommandLineArgs.Add("no-proxy-server", "1"); //Don't use a proxy server, always make direct connections. Overrides any other proxy server flags that are passed. //settings.CefCommandLineArgs.Add("debug-plugin-loading", "1"); //Dumps extra logging about plugin loading to the log file. //settings.CefCommandLineArgs.Add("disable-plugins-discovery", "1"); //Disable discovering third-party plugins. Effectively loading only ones shipped with the browser plus third-party ones as specified by --extra-plugin-dir and --load-plugin switches //settings.CefCommandLineArgs.Add("enable-system-flash", "1"); //Automatically discovered and load a system-wide installation of Pepper Flash. //settings.CefCommandLineArgs.Add("allow-running-insecure-content", "1"); //By default, an https page cannot run JavaScript, CSS or plugins from http URLs. This provides an override to get the old insecure behavior. Only available in 47 and above. //settings.CefCommandLineArgs.Add("enable-logging", "1"); //Enable Logging for the Renderer process (will open with a cmd prompt and output debug messages - use in conjunction with setting LogSeverity = LogSeverity.Verbose;) //settings.LogSeverity = LogSeverity.Verbose; // Needed for enable-logging to output messages //settings.CefCommandLineArgs.Add("disable-extensions", "1"); //Extension support can be disabled //settings.CefCommandLineArgs.Add("disable-pdf-extension", "1"); //The PDF extension specifically can be disabled //Load the pepper flash player that comes with Google Chrome - may be possible to load these values from the registry and query the dll for it's version info (Step 2 not strictly required it seems) //settings.CefCommandLineArgs.Add("ppapi-flash-path", @"C:\Program Files (x86)\Google\Chrome\Application\47.0.2526.106\PepperFlash\pepflashplayer.dll"); //Load a specific pepper flash version (Step 1 of 2) //settings.CefCommandLineArgs.Add("ppapi-flash-version", "20.0.0.228"); //Load a specific pepper flash version (Step 2 of 2) //NOTE: For OSR best performance you should run with GPU disabled: // `--disable-gpu --disable-gpu-compositing --enable-begin-frame-scheduling` // (you'll loose WebGL support but gain increased FPS and reduced CPU usage). // http://magpcss.org/ceforum/viewtopic.php?f=6&t=13271#p27075 //https://bitbucket.org/chromiumembedded/cef/commits/e3c1d8632eb43c1c2793d71639f3f5695696a5e8 //NOTE: The following function will set all three params //settings.SetOffScreenRenderingBestPerformanceArgs(); //settings.CefCommandLineArgs.Add("disable-gpu", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1"); //Disable Vsync //Disables the DirectWrite font rendering system on windows. //Possibly useful when experiencing blury fonts. //settings.CefCommandLineArgs.Add("disable-direct-write", "1"); // The following options control accessibility state for all frames. // These options only take effect if accessibility state is not set by IBrowserHost.SetAccessibilityState call. // --force-renderer-accessibility enables browser accessibility. // --disable-renderer-accessibility completely disables browser accessibility. //settings.CefCommandLineArgs.Add("force-renderer-accessibility", "1"); //settings.CefCommandLineArgs.Add("disable-renderer-accessibility", "1"); //Enables Uncaught exception handler settings.UncaughtExceptionStackSize = 10; // Off Screen rendering (WPF/Offscreen) if (settings.WindowlessRenderingEnabled) { //Disable Direct Composition to test https://github.com/cefsharp/CefSharp/issues/1634 //settings.CefCommandLineArgs.Add("disable-direct-composition", "1"); // DevTools doesn't seem to be working when this is enabled // http://magpcss.org/ceforum/viewtopic.php?f=6&t=14095 //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1"); } var proxy = ProxyConfig.GetProxyInformation(); switch (proxy.AccessType) { case InternetOpenType.Direct: { //Don't use a proxy server, always make direct connections. settings.CefCommandLineArgs.Add("no-proxy-server", "1"); break; } case InternetOpenType.Proxy: { settings.CefCommandLineArgs.Add("proxy-server", proxy.ProxyAddress); break; } case InternetOpenType.PreConfig: { settings.CefCommandLineArgs.Add("proxy-auto-detect", "1"); break; } } //settings.LogSeverity = LogSeverity.Verbose; if (DebuggingSubProcess) { var architecture = Environment.Is64BitProcess ? "x64" : "x86"; settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), IsSecure = true //treated with the same security rules as those applied to "https" URLs //SchemeHandlerFactory = new InMemorySchemeAndResourceHandlerFactory() }); settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeNameTest, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), IsSecure = true //treated with the same security rules as those applied to "https" URLs }); //You can use the http/https schemes - best to register for a specific domain settings.RegisterScheme(new CefCustomScheme { SchemeName = "https", SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(), DomainName = "cefsharp.com", IsSecure = true //treated with the same security rules as those applied to "https" URLs }); settings.RegisterScheme(new CefCustomScheme { SchemeName = "localfolder", SchemeHandlerFactory = new FolderSchemeHandlerFactory(rootFolder: @"..\..\..\..\CefSharp.Example\Resources", schemeName: "localfolder", //Optional param no schemename checking if null hostName: "cefsharp", //Optional param no hostname checking if null defaultPage: "home.html") //Optional param will default to index.html }); settings.RegisterExtension(new V8Extension("cefsharp/example", Resources.extension)); //This must be set before Cef.Initialized is called CefSharpSettings.FocusedNodeChangedEnabled = true; //Experimental option where bound async methods are queued on TaskScheduler.Default. //CefSharpSettings.ConcurrentTaskExecution = true; //Legacy Binding Behaviour doesn't work for cross-site navigation (navigating to a different domain) //See issue https://github.com/cefsharp/CefSharp/issues/1203 for details //CefSharpSettings.LegacyJavascriptBindingEnabled = true; //Exit the subprocess if the parent process happens to close //This is optional at the moment //https://github.com/cefsharp/CefSharp/pull/2375/ CefSharpSettings.SubprocessExitIfParentProcessClosed = true; //NOTE: Set this before any calls to Cef.Initialize to specify a proxy with username and password //One set this cannot be changed at runtime. If you need to change the proxy at runtime (dynamically) then //see https://github.com/cefsharp/CefSharp/wiki/General-Usage#proxy-resolution //CefSharpSettings.Proxy = new ProxyOptions(ip: "127.0.0.1", port: "8080", username: "******", password: "******"); if (!Cef.Initialize(settings, performDependencyCheck: !DebuggingSubProcess, browserProcessHandler: browserProcessHandler)) { throw new Exception("Unable to Initialize Cef"); } Cef.AddCrossOriginWhitelistEntry(BaseUrl, "https", "cefsharp.com", false); }
/// <summary> /// Handles the <see cref="E:ApplicationExit" /> event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private static void OnApplicationExit(object sender, EventArgs e) { Cef.Shutdown(); }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // Shutdown Cef Cef.Shutdown(); }