コード例 #1
0
        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");
            }
        }
コード例 #2
0
        /// <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;
        }
コード例 #3
0
 /// <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("", "");
 }
コード例 #4
0
ファイル: Form1.cs プロジェクト: ghkdwls30/Youtube
 // 쿠키 삭제 메소드
 private void DeleteCookie()
 {
     Cef.GetGlobalCookieManager().DeleteCookies("", "");
 }
コード例 #5
0
ファイル: WebView.cs プロジェクト: umbertomarotta/Playnite
 public void DeleteCookies(string url, string name)
 {
     Cef.GetGlobalCookieManager().DeleteCookies(url, name);
 }
コード例 #6
0
ファイル: Form1.cs プロジェクト: ghkdwls30/YoutubeLogin
 // 쿠키 삭제 메소드
 private async Task DeleteCookieAsync()
 {
     Cef.GetGlobalCookieManager().DeleteCookies("", "");
 }
コード例 #7
0
        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("ppapi-flash-path", @"C:\WINDOWS\SysWOW64\Macromed\Flash\pepflashplayer32_18_0_0_209.dll"); //Load a specific pepper flash version (Step 1 of 2)
            //settings.CefCommandLineArgs.Add("ppapi-flash-version", "18.0.0.209"); //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();
                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()
            });

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName           = CefSharpSchemeHandlerFactory.SchemeNameTest,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            settings.RegisterExtension(new CefExtension("cefsharp/example", Resources.extension));

            settings.FocusedNodeChangedEnabled = true;

            Cef.OnContextInitialized = delegate
            {
                var cookieManager = Cef.GetGlobalCookieManager();
                cookieManager.SetStoragePath("cookies", true);
                cookieManager.SetSupportedSchemes("custom");
            };

            if (!Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: !DebuggingSubProcess))
            {
                throw new Exception("Unable to Initialize Cef");
            }
        }
コード例 #8
0
        protected const int MaxTimerDelay = 1000 / 30;  // 30fps

        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Global CookieManager has been initialized, you can now set cookies
            var cookieManager = Cef.GetGlobalCookieManager();

            cookieManager.SetStoragePath("cookies", true);
            //cookieManager.SetSupportedSchemes(new string[] { "custom" });

            /*
             * if (cookieManager.SetCookie("custom://cefsharp/home.html", new Cookie
             * {
             *  Name = "CefSharpTestCookie",
             *  Value = "ILikeCookies",
             *  Expires = DateTime.Now.AddDays(1)
             * }))
             * {
             *  cookieManager.VisitUrlCookiesAsync("custom://cefsharp/home.html", false).ContinueWith(previous =>
             *  {
             *      if (previous.Status == TaskStatus.RanToCompletion)
             *      {
             *          var cookies = previous.Result;
             *
             *          foreach (var cookie in cookies)
             *          {
             *              Debug.WriteLine("CookieName:" + cookie.Name);
             *          }
             *      }
             *      else
             *      {
             *          Debug.WriteLine("No Cookies found");
             *      }
             *  });
             *
             *  cookieManager.VisitAllCookiesAsync().ContinueWith(t =>
             *  {
             *      if (t.Status == TaskStatus.RanToCompletion)
             *      {
             *          var cookies = t.Result;
             *
             *          foreach (var cookie in cookies)
             *          {
             *              Debug.WriteLine("CookieName:" + cookie.Name);
             *          }
             *      }
             *      else
             *      {
             *          Debug.WriteLine("No Cookies found");
             *      }
             *  });
             * }
             */

            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            //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);

                //It's possible to register a scheme handler for the default http and https schemes
                //In this example we register the FolderSchemeHandlerFactory for https://cefsharp.example
                //Best to include the domain name, so only requests for that domain are forwarded to your scheme handler
                //It is possible to intercept all requests for a scheme, including the built in http/https ones, be very careful doing this!

                /* var folderSchemeHandlerExample = new FolderSchemeHandlerFactory(rootFolder: @"..\..\..\..\CefSharp.Example\Resources",
                 *                                                      hostName: "cefsharp.example", //Optional param no hostname checking if null
                 *                                                      defaultPage: "home.html"); //Optional param will default to index.html
                 *
                 * context.RegisterSchemeHandlerFactory("https", "cefsharp.example", folderSchemeHandlerExample);
                 */
            }
        }
コード例 #9
0
        /// <summary>
        /// 页面加载完整后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            var cookieManager = Cef.GetGlobalCookieManager();

            //读取Cookie
            CookieVisitor visitor = new CookieVisitor();

            visitor.SendCookie += visitor_SendCookie;
            cookieManager.VisitAllCookies(visitor);

            #region
            //读取
            //var visitor = new CookieVisitor(all_cookies => {
            //    var sb = new StringBuilder();
            //    foreach (var nameValue in all_cookies)
            //        sb.AppendLine(nameValue.Item1 + " = " + nameValue.Item2);

            //    BeginInvoke(new MethodInvoker(() => {
            //        MessageBox.Show(sb.ToString());
            //    }));
            //});
            //cookieManager.VisitAllCookies(visitor);
            #endregion


            //执行Javascript代码
            if (e.Frame.IsMain)
            {
                browser.ExecuteScriptAsync(@"

 (function () {

    if (window.amazonBoundEvent) {
        var unameElem = document.getElementById('ap_email');
        var passwordElem = document.getElementById('ap_password');

        
        unameElem.value = window.amazonBoundEvent.aBName;
        passwordElem.value = window.amazonBoundEvent.aBPassword;
    }
    


    var elem = document.getElementById('signInSubmit');

    if (elem) {
        elem.addEventListener('click', function (e) {
            if (!window.amazonBoundEvent) {
                console.log('window.amazonBoundEvent does not exist.');
                return;
            }

            var uname = document.getElementById('ap_email').value;
            var password = document.getElementById('ap_password').value;

            if (uname == "" && password == "")
                return;

            if (uname == "" || password == "")
                return;

            window.amazonBoundEvent.raiseEvent('click', { unameField: uname, upasswordField: password });
        });
        //console.log(`Added click listener to ${elem.id}.`);
    }
})();
        ");
            }
        }
コード例 #10
0
        public BrowserController(SessionPreference sessionPreference, Logger logger)
        {
            this._sessionPreference = sessionPreference;
            this._logger            = logger;

            if (!Cef.IsInitialized)
            {
                var cefSettings = new CefSettings
                {
                    BrowserSubprocessPath = Path.Combine(
                        AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                        Environment.Is64BitProcess ? "x64" : "x86",
                        "CefSharp.BrowserSubprocess.exe")
                };
                cefSettings.CefCommandLineArgs.Add("enable-media-stream", "1");
                if (File.Exists(Path.Combine(Environment.CurrentDirectory, "video.y4m")))
                {
                    cefSettings.CefCommandLineArgs.Add("use-fake-device-for-media-stream");
                    cefSettings.CefCommandLineArgs.Add("--use-file-for-fake-video-capture", "video.y4m");
                }

                Cef.Initialize(cefSettings, performDependencyCheck: false, browserProcessHandler: null);
            }

            this._isv2 = this._sessionPreference.Name.ToLower().Contains("v2");
            if (this._isv2)
            {
                this._url = "https://chatroulette.com";
            }
            else
            {
                this._url = "https://chatroulette.com";
            }

            if (this._sessionPreference.Mod != "-1")
            {
                var m = this._sessionPreference.Mod;
                if (_isv2)
                {
                    m = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODUxOTM5ODYsInZhbHVlIjoiLT1TaDNyMWZmPS0ifQ.YM7YIilD-mhLmqIrl8KqcP0faV09MsGEiBDAqAB28fs";
                }
                else
                {
                    if (this._sessionPreference.Mod != "0")
                    {
                        if (this._sessionPreference.WithBan)
                        {
                            m = "0";
                        }
                        else
                        {
                            Cef.GetGlobalCookieManager().SetCookie(this._url,
                                                                   new Cookie()
                            {
                                Path = "/", Domain = this._url.Replace("https://", ""), Name = "counter", Value = this._sessionPreference.Mod
                            });
                            m = "-100";
                        }
                    }
                }
                this._logger.Trace("mod for current session: " + m);
                Cef.GetGlobalCookieManager().SetCookie(this._url,
                                                       new Cookie()
                {
                    Path = "/", Domain = this._url.Replace("https://", ""), Name = "mod", Value = m
                });
            }

            this._browser = new ChromiumWebBrowser(this._url);
            this._browser.ConsoleMessage +=
                (sender, args) =>
            {
                if (args.Message == "Couldn't fetch stats due to GetStats is not possible: OT.Subscriber is not connected cannot getStats")
                {
                    return;
                }
                this._logger.Trace($"Browser console message: {args.Message}");
                if (args.Message.Contains("partner banned by moderator"))
                {
                    this.BrowserBanState = true;
                }
                if (args.Message.Contains("Stream started"))
                {
                    this.BrowserBanState = false;
                }

                if (args.Message.Contains("Search started."))
                {
                    this.Status = Status.Wait;
                }
                if (args.Message.Contains("Client is now ready to begin."))
                {
                    this.Status = Status.EnableCamera;
                }
                if (args.Message.Contains("Setup publisher and camera turned on"))
                {
                    this.Status = Status.Start;
                }
                if (args.Message.Contains("Setup subscriber - success"))
                {
                    this.Status = Status.PartnerConnected;
                }
                if (args.Message.Contains("partner skipped") || args.Message.Contains("partner banned by moderator"))
                {
                    this.Status = Status.PutResult;
                }
            };

            this._browser.LoadingStateChanged += this.ChromeBrowserOnLoadingStateChanged;
            if (this._isv2)
            {
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
                backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
                backgroundWorker.RunWorkerAsync();
            }
        }
コード例 #11
0
ファイル: Form1.cs プロジェクト: dudwls7983/MyHomeAlert
 private void clearCookieButton_Click(object sender, EventArgs e)
 {
     Cef.GetGlobalCookieManager().DeleteCookies();
 }
コード例 #12
0
 private async Task <List <Cookie> > GetCookies(string url)
 {
     return(await Cef.GetGlobalCookieManager().VisitUrlCookiesAsync(url, true));
 }
コード例 #13
0
        public MainWindow()
        {
            startBrowser();

            InitializeComponent();

            //
            var    mngr = Cef.GetGlobalCookieManager();
            Cookie Ac   = new Cookie();

            Ac.HttpOnly = true;
            Ac.Name     = ".ASPXAUTH";
            Ac.Value    = "";
            mngr.SetCookieAsync(defaultSongUrl.ToString(), Ac);

            //Javascript funzt Handler
            Browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();

            //Soundcloud Visbility
            soundcloudView.Visibility = Visibility.Visible;

            //Settings Visbility
            settingsView.Visibility = Visibility.Collapsed;

            //Check if proxylist file exists
            using (StreamWriter w = File.AppendText("proxylist.txt"))

                //Check if accountlist file exists
                using (StreamWriter u = File.AppendText("accountlist.xml"))

                    //Check if additional song file exists
                    using (StreamWriter x = File.AppendText("songs.xml"))

                        //Check if License file exists
                        using (StreamWriter licenseFile = File.AppendText("license.txt"))

                            //Browser Requestcontext start
                            Browser.RequestContext = new RequestContext(new RequestContextSettings()
                            {
                                CachePath = System.IO.Directory.GetCurrentDirectory() + @"\Cache\Cache" + DateTime.Now.ToLongTimeString()
                            });

            //Default Soundcloud Song URL
            Browser.Address = defaultSongUrl;

            //Move default URL to textbox
            txtBox_songUrl.Text = defaultSongUrl;


            //default time between plays is set
            tbPlays.Text = Convert.ToString(timebetweenPlays / 1000);

            //Counter for generated plays is set
            genPlaysNumber.Content = automatedPlays;

            //load proxy liste :D
            loadProxyList();

            //Load Accountlist
            loadAccountsDataGrid();

            //Load additional Songs
            loadSoundCloudSongs();

            //Focus on webbrowser possible
            Browser.Focusable = true;

            //Max. Accounts for Followbot
            maxFollowAccountsTxtBox.Text = Convert.ToString(maxFollowAccounts);
            followedAccountsL.Content    = followedAccountsCount;

            // ♥ Helicoper Max Likes bla
            maxLikesTxtBox.Text = Convert.ToString(maxLikes);
            likedLabel.Content  = likedSongsCount;

            // Repost-o-mat
            maxRepostsTxt.Text   = Convert.ToString(maxreposts);
            repostsLabel.Content = repostedCount;

            //Menu Handler
            Browser.MenuHandler = new MenuHandler();

            //Mainframe finished loading
            Browser.FrameLoadEnd += (sender, args) =>
            {
                //Wait for the MainFrame to finish loading
                if (args.Frame.IsMain)
                {
                    //args.Frame.ExecuteJavaScriptAsync("alert('MainFrame finished loading');");



                    Trace.WriteLine("MainFrame finished loading");
                }
            };


            // Load the License
            loadLicense();

            // Validate License on Start
            validateLicenseOnStart();

            // Validation Shutdown
            if (licenseValid == false)
            {
                soundcloudView.Visibility      = Visibility.Hidden;
                settingsView.Visibility        = Visibility.Visible;
                soundcloudViewButton.IsEnabled = false;
            }
        }
コード例 #14
0
 public Task ClearCookies()
 {
     Cef.GetGlobalCookieManager().VisitAllCookies(new CookieVisitor());
     return(Task.CompletedTask);
 }
コード例 #15
0
 /// <summary>
 /// 删除cookie
 /// </summary>
 /// <param name="url"></param>
 /// <param name="name"></param>
 public async void DeleteCookie(string url = null, string name = null)
 {
     var cookieManager = Cef.GetGlobalCookieManager();
     await cookieManager.DeleteCookiesAsync(url, name);
 }
コード例 #16
0
 private void 清除登录信息ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Cef.GetGlobalCookieManager().DeleteCookies();
     myBrowser.Reload();
     MessageBox.Show("清除成功");
 }
コード例 #17
0
 public void DeleteAllCookies()
 {
     Cef.GetGlobalCookieManager().DeleteCookies();
 }
コード例 #18
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            log4net.Config.XmlConfigurator.Configure();
            m_Log = LogManager.GetLogger(this.GetType());

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var tmpFolder = System.IO.Path.GetTempPath() + "CotgBrowser_Cache";

            if (CotGBrowser.Properties.Settings.Default.ClearCache)
            {
                var dirInfo = new System.IO.DirectoryInfo(tmpFolder);

                foreach (System.IO.FileInfo file in dirInfo.GetFiles())
                {
                    file.Delete();
                }

                CotGBrowser.Properties.Settings.Default.ClearCache = false;
                CotGBrowser.Properties.Settings.Default.Save();
            }

            var settings = new CefSettings();

            settings.CachePath = tmpFolder;
            //settings.CefCommandLineArgs.Clear();
            settings.RemoteDebuggingPort = 8088;
            settings.CefCommandLineArgs.Add("enable-crash-reporter", "1");
            settings.CefCommandLineArgs.Add("proxy-auto-detect", "1");

            //single_process
            //settings.CefCommandLineArgs.Add("single_process", "1");
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");

            //WPF opt
            settings.WindowlessRenderingEnabled = true;
            settings.EnableInternalPdfViewerOffScreen();
            //settings.CefCommandLineArgs.Add("disable-gpu", "1");
            settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
            //settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1");

            //settings.CefCommandLineArgs.Add("enable-logging", "v=1");

            //settings.CefCommandLineArgs.Add("js-flags", "--max-old-space-size=2000");

            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "1");
            //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1");
            //settings.CefCommandLineArgs.Add("disable-canvas-aa", "1");
            //settings.CefCommandLineArgs.Add("disable-gpu-rasterization", "1");

            settings.MultiThreadedMessageLoop  = true;
            settings.FocusedNodeChangedEnabled = true;
            settings.LogSeverity = LogSeverity.Error;

            Cef.OnContextInitialized = delegate
            {
                var cookieManager = Cef.GetGlobalCookieManager();
                cookieManager.SetStoragePath("cookies", true);

                //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: false))
            {
                throw new Exception("Unable to Initialize Cef");
            }

            /*
             * Task.Run(() =>
             * {
             *  while (true)
             *  {
             *      try
             *      {
             *          //Application.Current.Dispatcher.Invoke(new Action(
             *          //  () => Cef.DoMessageLoopWork()));
             *          Cef.DoMessageLoopWork();
             *          System.Threading.Thread.Sleep(100);
             *      }
             *      catch (Exception eml)
             *      {
             *          m_Log.Error(eml.Message, eml);
             *      }
             *  }
             * });
             */

            //konf. fabryki
            IoCHelper.GetIoC();

            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile <GotGLib.NH.Schema.MapperProfile>();
            });
            Mapper.AssertConfigurationIsValid();

            m_Log.Info("Application started.");

            Application.Current.MainWindow = IoCHelper.GetIoC().Resolve <Views.MainWindow>();
            Application.Current.MainWindow.Show();
            Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            CotGNotifyIcon notify = new CotGNotifyIcon();

            IoCHelper.GetIoC().RegisterInstance <CotGNotifyIcon>(notify, new ContainerControlledLifetimeManager());
            notify.AppStarted();
        }
コード例 #19
0
        protected const int ThirtyTimesPerSecond = 1000 / 30;  //30fps

        void IBrowserProcessHandler.OnContextInitialized()
        {
            //The Global CookieManager has been initialized, you can now set cookies
            var cookieManager = Cef.GetGlobalCookieManager();

            cookieManager.SetStoragePath("cookies", true);
            cookieManager.SetSupportedSchemes(new string[] { "custom" });
            if (cookieManager.SetCookie("custom://cefsharp/home.html", new Cookie
            {
                Name = "CefSharpTestCookie",
                Value = "ILikeCookies",
                Expires = DateTime.Now.AddDays(1)
            }))
            {
                cookieManager.VisitUrlCookiesAsync("custom://cefsharp/home.html", false).ContinueWith(previous =>
                {
                    if (previous.Status == TaskStatus.RanToCompletion)
                    {
                        var cookies = previous.Result;

                        foreach (var cookie in cookies)
                        {
                            Debug.WriteLine("CookieName: " + cookie.Name);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No Cookies found");
                    }
                });

                cookieManager.VisitAllCookiesAsync().ContinueWith(t =>
                {
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        var cookies = t.Result;

                        foreach (var cookie in cookies)
                        {
                            Debug.WriteLine("CookieName: " + cookie.Name);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No Cookies found");
                    }
                });
            }

            //The Request Context has been initialized, you can now set preferences, like proxy server settings
            //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);

                //string error;
                //var dicts = new List<string> { "en-GB", "en-US" };
                //var success = context.SetPreference("spellcheck.dictionaries", dicts, out error);

                //The no-proxy-server flag is set in CefExample.cs class, you'll have to remove that before you can test
                //this code out
                //var v = new Dictionary<string, string>
                //{
                //    ["mode"] = "fixed_servers",
                //    ["server"] = "scheme://*****:*****@"..\..\..\..\CefSharp.Example\Resources",
                                                                                hostName: "cefsharp.example", //Optional param no hostname checking if null
                                                                                defaultPage: "home.html");    //Optional param will default to index.html

                context.RegisterSchemeHandlerFactory("https", "cefsharp.example", folderSchemeHandlerExample);
            }
        }
コード例 #20
0
ファイル: App.xaml.cs プロジェクト: coder5110/wpf
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (m_mutex.WaitOne(TimeSpan.Zero, true))
            {
                Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

                HtmlNode.ElementsFlags.Remove("form");
                HtmlNode.ElementsFlags.Remove("option");
                System.Net.ServicePointManager.Expect100Continue = false;
                ServicePointManager.SecurityProtocol             = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls |
                                                                   SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                LicenseManagerViewModel licenseManagerViewModel = new LicenseManagerViewModel()
                {
                    Model = LicenseInfo.GetForCurrentDevice()
                };

                LicenseChecker licenseChecker = new LicenseChecker()
                {
                    DataContext = licenseManagerViewModel
                };

                licenseChecker.ShowDialog();

                if (!(licenseManagerViewModel.IsLicenseValid ?? false) && licenseManagerViewModel.IsCheckingFinished &&
                    licenseManagerViewModel.IsLicenseServerReachable)
                {
                    LicenseManager lm = new LicenseManager()
                    {
                        DataContext = licenseManagerViewModel
                    };

                    lm.ShowDialog();
                }

                if (licenseManagerViewModel.IsLicenseValid ?? false)
                {
                    using (StreamWriter writer = new StreamWriter("license.key"))
                    {
                        writer.WriteLine(licenseManagerViewModel.Model.Key);
                    }

                    string tierStr = licenseManagerViewModel.LicenseKey.Substring(14, 1);

                    Tier?tier = null;

                    if (tierStr == "N")
                    {
                        tier = Tier.Novice;
                    }
                    else if (tierStr == "S")
                    {
                        tier = Tier.Standart;
                    }
                    else if (tierStr == "U")
                    {
                        tier = Tier.Ultimate;
                    }

                    if (tier != null)
                    {
                        TierControl.Init((Tier)tier);

                        AutoUpdater.AppTitle = "Project Destroyer";
                        AutoUpdater.Start("https://projectdestroyer.com/update/ui.xml");

                        CefSharp.Cef.Initialize();

                        Cef.GetGlobalCookieManager()
                        .SetCookie("https://www.google.com", new Cookie()
                        {
                            Name  = "NID",
                            Value =
                                "114=VmK5Yof_gASwTsA4f9mDhik59gO5ivFGNdwRFZ5eqb13IrO4y_oc7cqKOjD4d8VTeHqlSFtXecyGVpHTHCzi3H56q67Wic82SSme36ed0eSFnLAbZ7TzEMyMT83YvPTXDSB_UMNus_iOrgmpz2h1UHE5qMHImEeKqTNfJ-ufhJs",
                            Domain  = ".google.com",
                            Secure  = true,
                            Expires = DateTime.Now.AddDays(364),
                            Path    = "/"
                        });

                        Cef.GetGlobalCookieManager()
                        .SetCookie("https://www.google.com", new Cookie()
                        {
                            Name  = "SID",
                            Value =
                                "RQUZKqa2lvg8bV2MOpudssKUIM1m4ePTnSHRw8vJdLi5s6OqsMm-nauRbe30Pvd6E04m4g.",
                            Domain  = ".google.com",
                            Secure  = true,
                            Expires = DateTime.Now.AddDays(364),
                            Path    = "/"
                        });

                        Cef.GetGlobalCookieManager()
                        .SetCookie("https://www.google.com", new Cookie()
                        {
                            Name  = "HSID",
                            Value =
                                "AmU2jxCL2p_HH0ZPd",
                            Domain  = ".google.com",
                            Secure  = true,
                            Expires = DateTime.Now.AddDays(364),
                            Path    = "/"
                        });

                        Cef.GetGlobalCookieManager()
                        .SetCookie("https://www.google.com", new Cookie()
                        {
                            Name  = "SSID",
                            Value =
                                "A-zucxjV69YuQrG9R",
                            Domain  = ".google.com",
                            Secure  = true,
                            Expires = DateTime.Now.AddDays(364),
                            Path    = "/"
                        });

                        Cef.GetGlobalCookieManager()
                        .SetCookie("https://www.google.com", new Cookie()
                        {
                            Name  = "APISID",
                            Value =
                                "kKGH9LEmsKlHE1z5/AHkUX3rAZaMPSmMZI",
                            Domain  = ".google.com",
                            Secure  = true,
                            Expires = DateTime.Now.AddDays(364),
                            Path    = "/"
                        });

                        Cef.GetGlobalCookieManager()
                        .SetCookie("https://www.google.com", new Cookie()
                        {
                            Name  = "SAPISID",
                            Value =
                                "IbeC7mNDggiLVl1C/APfpkXK9im_Fx6R75",
                            Domain  = ".google.com",
                            Secure  = true,
                            Expires = DateTime.Now.AddDays(364),
                            Path    = "/"
                        });

                        //var ccm = CefSharp.Cef.GetGlobalCookieManager();

                        //foreach (string line in str.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                        //{
                        //    string[] fields = line.Split(new[] { '\t' });

                        //    CefSharp.Cookie cookie = new CefSharp.Cookie()
                        //    {
                        //        Domain = fields[0],
                        //        Path = fields[2],
                        //        Secure = bool.Parse(fields[3]),
                        //        Expires = TimeHelper.UnixTimeStampToDateTime(double.Parse(fields[4]) < uint.MaxValue
                        //            ? double.Parse(fields[4])
                        //            : int.MaxValue),
                        //        Name = fields[5],
                        //        Value = fields[6]
                        //    };

                        //    string url = cookie.Secure ? "https://" : "http://";
                        //    url = $"{url}{(cookie.Domain[0] != '.' ? cookie.Domain : cookie.Domain.Substring(1))}/";

                        //    bool ress = ccm.SetCookie(url, cookie);
                        //}

                        MainWindow appWindow = new MainWindow()
                        {
                            DataContext = new AppViewModel()
                        };
                        appWindow.ShowDialog();

                        CefSharp.Cef.Shutdown();
                    }
                    else
                    {
                        MessageBox.Show("Your tier does not exists. Contact with support.");
                    }
                }

                Application.Current?.Shutdown();

                m_mutex.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("Only one instance of Project Destroyer at a time");

                Application.Current?.Shutdown();
            }
        }
コード例 #21
0
 public void ClearData()
 {
     Cef.GetGlobalCookieManager().DeleteCookies();
 }
コード例 #22
0
ファイル: MainWindow.cs プロジェクト: AlexS4v/ORB4
        public MainWindow()
        {
            InitializeComponent();

            Current = this;

            this.Resize += OnWinResize;

            string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            _cefSettings = new CefSettings()
            {
                CachePath = null
            };

            _cefSettings.CefCommandLineArgs.Add("--disable-cache", "1");
            _cefSettings.CefCommandLineArgs.Add("--disable-application-cache", "1");
            _cefSettings.CefCommandLineArgs.Add("--disable-session-storage", "1");
            _cefSettings.CefCommandLineArgs.Add("--disable-local-storage", "1");
            _cefSettings.CefCommandLineArgs.Add("--disable-web-security", "1");

            if (System.IO.File.Exists($"{AppData}\\ORB\\cef.log"))
            {
                System.IO.File.Delete($"{AppData}\\ORB\\cef.log");
            }

            _cefSettings.LogFile     = $"{AppData}\\ORB\\cef.log";
            _cefSettings.LogSeverity = LogSeverity.Error | LogSeverity.Info | LogSeverity.Warning;

            Cef.Initialize(_cefSettings);

            if (!Cef.IsInitialized)
            {
                throw new Exception("Couldn't initialize CEF.");
            }

            Logger.MainLogger.Log(Logger.LogTypes.Info, "CEF.Initialize -> Success");

            CefSharpSettings.LegacyJavascriptBindingEnabled = true;

            var manager = Cef.GetGlobalCookieManager();

            _server = new WebServer();
            _server.Start();

            Logger.MainLogger.Log(Logger.LogTypes.Info, "HTTPServer.Start -> Success");

            if (System.IO.File.Exists($"{AppData}\\ORB\\Private\\Key"))
            {
                Engine.ApiKey = System.IO.File.ReadAllText($"{AppData}\\ORB\\Private\\Key");
                Logger.MainLogger.Log(Logger.LogTypes.Info, "APIKey.Load -> Success");
            }

            _browser = new ChromiumWebBrowser($"{_server.Url}html/mainwindow.html")
            {
                Dock = DockStyle.Fill
            };

            Logger.MainLogger.Log(Logger.LogTypes.Info, "BrowserObject.Create -> Success");
            _browser.RegisterJsObject("cSharpTools", new CSharpTools(ref _server.Engine, ref Current, ref _server));
            Logger.MainLogger.Log(Logger.LogTypes.Info, "BrowserObject.RegisterJS -> Success");
            _browser.BackColor = Color.Black;
            this.BackColor     = Color.Black;

            manager.SetCookie(_server.Url, new CefSharp.Cookie()
            {
                Path  = "/",
                Name  = "token",
                Value = Convert.ToBase64String(_server.Token)
            });

            Logger.MainLogger.Log(Logger.LogTypes.Info, "CookieManager.SetCookie -> Success");
            _browser.Dock = DockStyle.None;

            _browser.IsBrowserInitializedChanged += InitializeStatus;
            this.Controls.Add(_browser);
            _browser.Paint += BrowserPaint;

            Color panelColor = _server.Engine.LocalSettings.NightMode ?
                               Color.FromArgb(32, 31, 36) : Color.White;

            if (!_server.Engine.LocalSettings.NightMode)
            {
                _loadingPanel = new Panel
                {
                    Dock      = DockStyle.Fill,
                    BackColor = panelColor
                };

                this.Controls.Add(_loadingPanel);
                _loadingPanel.BringToFront();
            }

            BackColor = Color.Black;
        }