Exemplo n.º 1
1
        private static async void MainAsync(string cachePath, double zoomLevel)
        {
            var browserSettings = new BrowserSettings();
            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);

                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);

                await LoadPageAsync(browser, "http://github.com");

                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
            }
        }
Exemplo n.º 2
1
        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);

                    var preferences = requestContext.GetAllPreferences(true);

                    // 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);
                }
        }
Exemplo n.º 3
0
        private static async void MainAsync(string cachePath, double zoomLevel)
        {
            var browserSettings        = new BrowserSettings();
            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.IsMainFrame)
                            {
                                b.SetZoomLevel(zoomLevel);
                            }
                        };
                    }
                    await LoadPageAsync(browser);

                    // Wait for the screenshot to be taken.
                    await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);

                    await LoadPageAsync(browser, "http://github.com");

                    // Wait for the screenshot to be taken.
                    await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
                }
        }
        static async Task <string> GetPageSource(string url)
        {
            BrowserSettings browserSettings = new BrowserSettings
            {
                FileAccessFromFileUrls    = CefState.Disabled,
                JavascriptAccessClipboard = CefState.Disabled,
                JavascriptCloseWindows    = CefState.Disabled,
                JavascriptDomPaste        = CefState.Disabled,
                Plugins = CefState.Disabled,
                UniversalAccessFromFileUrls = CefState.Disabled,
                WebSecurity = CefState.Enabled,
            };

            RequestContextSettings requestContextSettings = new RequestContextSettings
            {
                CachePath = null,
                IgnoreCertificateErrors = false,
                PersistSessionCookies   = false,
                PersistUserPreferences  = false,
            };

            // RequestContext can be shared between browser instances and allows for custom settings
            // e.g. CachePath
            using (RequestContext requestContext = new RequestContext(requestContextSettings))
                using (ChromiumWebBrowser browser = new ChromiumWebBrowser(url, browserSettings, requestContext))
                {
                    await LoadPageAsync(browser);

                    return("Hello World!!\n");
                }
        }
Exemplo n.º 5
0
        protected virtual async void AsyncBrowser()
        {
            RequestContextSettings reqSettings = new RequestContextSettings {
                CachePath = CachePath
            };

            using (RequestContext context = new RequestContext(reqSettings))
            {
                _browser = new ChromiumWebBrowser(Uri.ToString(), _browserSettings, context);
                BrowserPreInit?.Invoke(_browser, new EventArgs());
                _browser.Size           = new Size((int)_windowWidth, (int)_windowHeight);
                _browser.NewScreenshot += Browser_NewScreenshot;

                _browser.BrowserInitialized += _browser_BrowserInitialized;

                if (_zoomLevel > 1)
                {
                    _browser.FrameLoadStart += (s, argsi) =>
                    {
                        if (argsi.Frame.IsMain)
                        {
                            ((ChromiumWebBrowser)s).SetZoomLevel(_zoomLevel);
                        }
                    };
                }

                await LoadPageAsync(_browser);
            }

            //If while we waited any JS commands were queued, then run those now
            ExecQueuedJS();
        }
Exemplo n.º 6
0
        public void StartOffscreenRender(string url)
        {
#if WITHCEF
            var settings = new CefSharp.OffScreen.CefSettings()
            {
                //By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
                CachePath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache"),
            };

            // play with surfaces
            settings.SetOffScreenRenderingBestPerformanceArgs();

            //Perform dependency check to make sure all relevant resources are in our output directory.
            // Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

            var rqs = new RequestContextSettings();
            rqs.CachePath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
            var rq = new RequestContext(rqs, null);

            var bs = new BrowserSettings();
            bs.BackgroundColor = 0xff000000;

            this.theOffscreenBrowser      = new CefSharp.OffScreen.ChromiumWebBrowser(url, bs, rq);
            this.theOffscreenBrowser.Size = new System.Drawing.Size(400, 800);
            this.theOffscreenBrowser.LoadingStateChanged += TheBrowser_LoadingStateChanged;
            this.theOffscreenBrowser.FrameLoadEnd        += TheOffscreenBrowser_FrameLoadEnd;
        public BrowserWindow(Configuration configuration)
        {
            CefSettings cefSharpSettings = new CefSettings {
                LogSeverity = LogSeverity.Disable
            };

            Cef.Initialize(cefSharpSettings);
            ShowActivated = true;
            Url           = configuration.HttpUrl();
            InitializeComponent();
            Browser.Address = Url;

            var requestContextSettings = new RequestContextSettings
            {
                CachePath = Storage.BrowserCachePath
            };

            Browser.RequestContext = new RequestContext(requestContextSettings);
            var position = Storage.RestorePosition();

            if (position.HasValue)
            {
                Left   = position.Value.x;
                Top    = position.Value.y;
                Width  = position.Value.width;
                Height = position.Value.height;
            }
        }
Exemplo n.º 8
0
        private void AddNewTab(Model.Site site)
        {
            Regex rgx      = new Regex("[^\\w\\d\\-_\\.]");
            var   cacheExt = rgx.Replace(site.Name, "");

            cacheExt += "-" + rgx.Replace(site.Url, "");
            var requestContextSettings = new RequestContextSettings {
                CachePath = "cache-" + cacheExt
            };
            var requestContext = new RequestContext(requestContextSettings);

            // Create a browser component
            var chromeBrowser = new ChromiumWebBrowser(site.Url)
            {
                RequestContext = requestContext
            };

            // Add it to the form and fill it to the form window.
            tab.TabPages.Insert(tab.TabCount - 1, site.Name);
            tab.TabPages[tab.TabPages.Count - 2].Controls.Add(chromeBrowser);

            chromeBrowser.Dock           = DockStyle.Fill;
            chromeBrowser.RequestHandler = new RequestHandler {
                Url = site.Url
            };
            chromeBrowser.LifeSpanHandler = new LifeSpanHandler {
                Url = site.Url
            };
            chromeBrowser.DownloadHandler = new DownloadHandler();

            ChromeBrowsersList.Add(chromeBrowser);

            tab.Refresh();
            tab.SelectTab(tab.TabCount - 2);
        }
Exemplo n.º 9
0
        /*
         * Some comments might be outdated. shanty#0001 if you need me.
         */
        public MainWindow()
        {
            InitializeComponent();
            RequestContextSettings requestContextSettings = new RequestContextSettings();

            requestContextSettings.PersistSessionCookies  = false;
            requestContextSettings.PersistUserPreferences = false;
            cef1.RequestContext = new RequestContext(requestContextSettings); // Makes browser1 have its own seperate context settings, essentially cookies
            cef2.RequestContext = new RequestContext(requestContextSettings); // Same as above but for browser2
        }
Exemplo n.º 10
0
        /// <summary>
        /// 隔离Cookie
        /// </summary>
        public void IsolationCookie()
        {
            RequestContextSettings requestContextSettings = new RequestContextSettings();

            requestContextSettings.PersistSessionCookies  = false;
            requestContextSettings.PersistUserPreferences = false;

            //string BaseUrl = "www.baidu.com";
            //web = new ChromiumWebBrowser(BaseUrl);
            browser.RequestContext = new RequestContext(requestContextSettings);
        }
Exemplo n.º 11
0
        public static void Init(CefConfiguration cefConfiguration)
        {
            Cef.EnableWaitForBrowsersToClose();

            InitInternal(cefConfiguration);

            var requestContextSettings = new RequestContextSettings {
                CachePath = cefConfiguration.CachePathRequest
            };

            s_requestContext = new RequestContext(requestContextSettings);
        }
        public async void Start()
        {
            // Settings modifiers
            this.settings.WindowlessFrameRate = 60;
            this.settings.BackgroundColor     = 0x00;

            // CEF init with custom settings
            var cefSettings = new CefSettings();

            cefSettings.CefCommandLineArgs["disable-extensions"]                        = "1";
            cefSettings.CefCommandLineArgs["disable-gpu"]                               = "1";
            cefSettings.CefCommandLineArgs["disable-gpu-compositing"]                   = "1";
            cefSettings.CefCommandLineArgs["enable-begin-frame-scheduling"]             = "1";
            cefSettings.CefCommandLineArgs["enable-experimental-web-platform-features"] = "1";
            cefSettings.CefCommandLineArgs["enable-media-stream"]                       = "1";
            cefSettings.CefCommandLineArgs["enable-precise-memory-info"]                = "1";
            cefSettings.CefCommandLineArgs["autoplay-policy"]                           = "no-user-gesture-required";
            cefSettings.CefCommandLineArgs.Remove("mute-audio");
            Cef.Initialize(cefSettings);

            // Request context
            var reqCtxSettings = new RequestContextSettings
            {
                CachePath = "",
                IgnoreCertificateErrors = false,
                PersistSessionCookies   = false,
                PersistUserPreferences  = false,
            };

            this.requestContext = new RequestContext(reqCtxSettings);

            // Browser window
            this.webBrowser                 = new ChromiumWebBrowser("about:blank", this.settings, this.requestContext, false);
            this.webBrowser.MenuHandler     = this;
            this.webBrowser.LifeSpanHandler = this;

            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            this.webBrowser.RegisterAsyncJsObject("unityCaller", new BoundObject(this.runner));
            this.webBrowser.CreateBrowser();
            ResizeTask rz = new ResizeTask(startsize);

            // Resize and wait for init
            Resize(rz.width, rz.height);
            WaitForBrowserInit();

            // Bind events
            this.webBrowser.Paint               += WebBrowser_Paint;
            this.webBrowser.LoadError           += WebBrowser_LoadError;
            this.webBrowser.LoadingStateChanged += WebBrowser_LoadingStateChanged;

            // Load initial page (TEST / TEMP)
            await LoadPageAsync(starturl);
        }
Exemplo n.º 13
0
        private ChromiumWebBrowser CreateBrowser(string url, string cachePath)
        {
            var browserSettings = new BrowserSettings();

            browserSettings.WindowlessFrameRate = 1;
            var requestContextSettings = new RequestContextSettings {
                CachePath = cachePath
            };
            var requestContext = new RequestContext(requestContextSettings);

            return(new ChromiumWebBrowser(url, browserSettings, requestContext));
        }
Exemplo n.º 14
0
        private SharpTab AddNewBrowser(FATabStripItem tabStrip, String url)
        {
            if (url == "")
            {
                url = NewTabURL;
            }

            ChromiumWebBrowser browser = new ChromiumWebBrowser(url);
            var requestContextSettings = new RequestContextSettings {
                CachePath = GetAppDir("Cache/tmp_" + TabPages.Items.Count + "cache")
            };

            browser.RequestContext = new RequestContext(requestContextSettings);
            // set config
            ConfigureBrowser(browser);

            // set layout
            browser.Dock = DockStyle.Fill;
            tabStrip.Controls.Add(browser);
            browser.BringToFront();

            // add events
            browser.StatusMessage       += Browser_StatusMessage;
            browser.LoadingStateChanged += Browser_LoadingStateChanged;
            browser.TitleChanged        += Browser_TitleChanged;
            browser.LoadError           += Browser_LoadError;
            browser.AddressChanged      += Browser_URLChanged;
            browser.DownloadHandler      = dHandler;
            browser.MenuHandler          = mHandler;
            browser.LifeSpanHandler      = lHandler;
            browser.KeyboardHandler      = kHandler;
            browser.RequestHandler       = rHandler;

            // new tab obj
            SharpTab tab = new SharpTab {
                IsOpen      = true,
                Browser     = browser,
                Tab         = tabStrip,
                PrevURL     = null,
                OrigURL     = url,
                CurURL      = url,
                Title       = "New Tab",
                DateCreated = DateTime.Now
            };

            // save tab obj in tabstrip
            tabStrip.Tag = tab;

            /*if (url.StartsWith(InternalURL + ":")) {
             *      browser.JavascriptObjectRepository.Register("host", host, true, BindingOptions.DefaultBinder);
             * }*/
            return(tab);
        }
Exemplo n.º 15
0
        public BrowserControl()
        {
            InitializeComponent();

            var requestContextSettings = new RequestContextSettings {
                CachePath = "cache_context", PersistSessionCookies = true
            };
            RequestContext context = new RequestContext(requestContextSettings);

            browserControl.RequestContext = context;

            // GoTo(Address);
        }
Exemplo n.º 16
0
        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);

                var preferences = requestContext.GetAllPreferences(true);

                // 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);
            }
        }
Exemplo n.º 17
0
        public async void Start()
        {
            // Settings modifiers
            this.settings.WindowlessFrameRate = 60;
            this.settings.BackgroundColor     = 0x00;

            // CEF init with custom settings
            var cefSettings = new CefSettings();

            cefSettings.CefCommandLineArgs["disable-extensions"]                        = "1";
            cefSettings.CefCommandLineArgs["disable-gpu"]                               = "1";
            cefSettings.CefCommandLineArgs["disable-gpu-compositing"]                   = "1";
            cefSettings.CefCommandLineArgs["enable-begin-frame-scheduling"]             = "1";
            cefSettings.CefCommandLineArgs["enable-experimental-web-platform-features"] = "1";
            cefSettings.CefCommandLineArgs["enable-media-stream"]                       = "1";
            cefSettings.CefCommandLineArgs["enable-precise-memory-info"]                = "1";
            cefSettings.CefCommandLineArgs["autoplay-policy"]                           = "no-user-gesture-required";
            cefSettings.CefCommandLineArgs.Remove("mute-audio");
            Cef.Initialize(cefSettings);

            // Request context
            var reqCtxSettings = new RequestContextSettings
            {
                CachePath = "",
                IgnoreCertificateErrors = false,
                PersistSessionCookies   = false,
                PersistUserPreferences  = false,
            };

            this.requestContext = new RequestContext(reqCtxSettings);

            // Browser window
            this.webBrowser                 = new ChromiumWebBrowser("about:blank", this.settings, this.requestContext, false);
            this.webBrowser.MenuHandler     = this;
            this.webBrowser.LifeSpanHandler = this;
            this.webBrowser.CreateBrowser();

            // Resize and wait for init
            Resize(1024, 768);
            WaitForBrowserInit();

            // Bind events
            this.webBrowser.Paint               += WebBrowser_Paint;
            this.webBrowser.LoadError           += WebBrowser_LoadError;
            this.webBrowser.LoadingStateChanged += WebBrowser_LoadingStateChanged;

            // Load initial page (TEST / TEMP)
            await LoadPageAsync("https://www.youtube.com/watch?v=KaOC9danxNo");
        }
Exemplo n.º 18
0
        private static RequestContext CreateContext()
        {
            var settings = new CefSettings()
            {
                CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")
            };

            Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

            RequestContextSettings requestContextSettings = new RequestContextSettings();

            requestContextSettings.PersistSessionCookies  = false;
            requestContextSettings.PersistUserPreferences = false;
            return(new RequestContext(requestContextSettings));
        }
        public FormSOBrowser(string cacheDirName, string url)
        {
            _cacheDirName = cacheDirName;
            _url          = url;

            InitializeComponent();
            Load += OnLoad;

            //Only perform layout when control has completly finished resizing
            ResizeBegin += (s, e) => SuspendLayout();
            ResizeEnd   += (s, e) => ResumeLayout(true);

#if DEBUG
            outputLabel.Visible = true;
#else
            outputLabel.Visible = false;
#endif


            // cache path
            //To get the location the assembly normally resides on disk or the install directory
            string path      = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            string directory = Path.GetDirectoryName(path);
            string localpath = new Uri(directory).LocalPath;
            if (!Directory.Exists(localpath))
            {
                Directory.CreateDirectory(localpath);
            }

            localpath += "\\" + cacheDirName;
            if (!Directory.Exists(localpath))
            {
                Directory.CreateDirectory(localpath);
            }


            requestContextSettings = new RequestContextSettings
            {
                CachePath               = localpath,
                PersistSessionCookies   = true,
                PersistUserPreferences  = true,
                IgnoreCertificateErrors = true,
                AcceptLanguageList      = "es-419, es;q=0.8"
            };

            requestContext = new RequestContext(requestContextSettings);
        }
        public MiniChatWindow()
        {
            //cef settings
            RequestContextSettings requestContextSettings = new RequestContextSettings();

            requestContextSettings.PersistSessionCookies  = false;
            requestContextSettings.PersistUserPreferences = false;
            requestContextSettings.CachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\TwitchAssistant\Streamer";
            ChatBrowser = new ChromiumWebBrowser();
            ChatBrowser.RequestContext = new RequestContext(requestContextSettings);
            ChatBrowser.MenuHandler    = new MyCustomMenuHandler();
            ChatBrowser.BrowserSettings.BackgroundColor = 0x00;
            ChatBrowser.Name = "ChatBrowser";

            this.DataContext = new MiniChatViewModel(this);
            InitializeComponent();
            BrowserContainer.Children.Add(ChatBrowser);
            ChatBrowser.Address = $"https://www.twitch.tv/popout/{ ConfigSet.Config.BotConfig.StreamName }/chat?popout=";
        }
Exemplo n.º 21
0
        protected virtual async void AsyncBrowser()
        {
            RequestContextSettings contextSettings = new RequestContextSettings()
            {
                CachePath = CachePath,
            };

            using (RequestContext context = new RequestContext(contextSettings, RequestContextHandler))
            {
                foreach (CefCustomScheme scheme in SchemeHandlers)
                {
                    context.RegisterSchemeHandlerFactory(scheme.SchemeName, scheme.DomainName, scheme.SchemeHandlerFactory);
                }

                SteamVR_WebKit.Log("Browser Initialising for " + _overlayKey);

                _browser = new ChromiumWebBrowser(Uri.ToString(), _browserSettings, context, false);
                Browser.RenderProcessMessageHandler = MessageHandler;
                BrowserPreInit?.Invoke(_browser, new EventArgs());
                _browser.Size = new Size((int)_windowWidth, (int)_windowHeight);
                //_browser.NewScreenshot += Browser_NewScreenshot;

                _browser.BrowserInitialized += _browser_BrowserInitialized;

                _browser.CreateBrowser();

                if (_zoomLevel > 1)
                {
                    _browser.FrameLoadStart += (s, argsi) =>
                    {
                        if (argsi.Frame.IsMain)
                        {
                            ((ChromiumWebBrowser)s).SetZoomLevel(_zoomLevel);
                        }
                    };
                }

                await LoadPageAsync(_browser);
            }

            //If while we waited any JS commands were queued, then run those now
            ExecQueuedJS();
        }
Exemplo n.º 22
0
        public void CreateLockedBrowser()
        {
            Browser = new ChromiumWebBrowser();

            // This request handler checks links before browsing to them to see if they are allowed
            JRequestHandler RequestHandler = new JRequestHandler();

            RequestHandler.Prefixes = Prefixes;
            RequestHandler.Prefixes.Add(Address);
            RequestHandler.IsLockedSite = IsLockedSite;


            // In actual practice this guy needs to be added to those who use him's prefix list.
            RequestHandler.Prefixes.Add("fls.doubleclick.net");

            // Add the steps from the site to the request handler
            RequestHandler.Steps = Steps;


            Browser.RequestHandler = RequestHandler;



            // The lifespan handler handles things like popups. Which don't need top happen.
            Browser.LifeSpanHandler = new JLifeSpanHandler();


            // Make each of these with a new cash path so they don't track eachother
            var requestContextSettings = new RequestContextSettings {
                CachePath = ""
            };
            var requestcontext = new RequestContext(requestContextSettings);

            Browser.RequestContext = requestcontext;

            // Navigate to the site and give it an id I can find
            Browser.Address = Address;


            this.Children.Add(Browser);
        }
Exemplo n.º 23
0
        public TabItem(IContur contur)
        {
            string currDir = AppDomain.CurrentDomain.BaseDirectory;

            Index = _indexCounter++;
            DirectoryInfo dirInfo  = Directory.CreateDirectory(currDir + "\\Cache\\Inst" + Index);
            var           settings = new RequestContextSettings
            {
                IgnoreCertificateErrors = contur.IgnoreCertificateErrors,
                PersistSessionCookies   = contur.PersistSessionCookies,
                CachePath = dirInfo.FullName,
            };

            Browser = new ChromiumWebBrowser();
            Browser.RequestContext = new RequestContext(settings);
            Header          = contur.Header;
            Browser.Address = contur.Address;
            CloseTab        = new Command(OnCloseTab);
            MainJS          = new Command(OnMainJS);
            ShowDevTools    = new Command(OnShowDevTools);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates a new <see cref="ChromiumElementFormatter"/>.
        /// </summary>
        /// <param name="browser">The browser that will be used to format the text.</param>
        public ChromiumElementFormatter()
        {
            // Start a browser that will be measuring all our text
            var browserSettings = new BrowserSettings()
            {
                WindowlessFrameRate = 1,
                Javascript          = CefState.Enabled,
            };
            var requestContextSettings = new RequestContextSettings()
            {
                CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache"),
            };

            _requestContext = new RequestContext(requestContextSettings);
            _browser        = new ChromiumWebBrowser("http://simplecircuit/", browserSettings, _requestContext, true);
            _browser.LoadHtml(_browserHtml, "http://simplecircuit/");

            var task = _browser.WaitForInitialLoadAsync();

            task.Wait();
        }
Exemplo n.º 25
0
        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);

                    // 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.
                    await browser.ScreenshotAsync(true).ContinueWith(DisplayBitmap);

                    await LoadPageAsync(browser, "http://github.com");

                    // Wait for the screenshot to be taken.
                    await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
                }
        }
Exemplo n.º 26
0
        protected virtual async void AsyncBrowser()
        {
            RequestContextSettings reqSettings = new RequestContextSettings {
                CachePath = CachePath
            };

            using (RequestContext context = new RequestContext(reqSettings))
            {
                _browser = new ChromiumWebBrowser(Uri.ToString(), _browserSettings, context);
                if (_autoKeyboard)
                {
                    _browser.RegisterJsObject("keyboard", new Keyboard(DashboardOverlay));
                    _autoKeyboardJS = File.ReadAllText("Resources/keyboard.js");
                }
                BrowserPreInit?.Invoke(_browser, new EventArgs());
                _browser.Size           = new Size((int)_windowWidth, (int)_windowHeight);
                _browser.NewScreenshot += Browser_NewScreenshot;

                _browser.BrowserInitialized += _browser_BrowserInitialized;

                if (_zoomLevel > 1)
                {
                    _browser.FrameLoadStart += (s, argsi) =>
                    {
                        if (argsi.Frame.IsMain)
                        {
                            ((ChromiumWebBrowser)s).SetZoomLevel(_zoomLevel);
                        }
                    };
                }
                // register handler for keyboard showing
                EventHandler <LoadingStateChangedEventArgs> handler = _browserPageLoaded;
                _browser.LoadingStateChanged += handler;

                await LoadPageAsync(_browser);
            }

            //If while we waited any JS commands were queued, then run those now
            ExecQueuedJS();
        }
Exemplo n.º 27
0
        public AuthBrowserWindow(bool IsStreamerAuth)
        {
            //Cef settings
            RequestContextSettings requestContextSettings = new RequestContextSettings();

            requestContextSettings.PersistSessionCookies  = false;
            requestContextSettings.PersistUserPreferences = false;
            if (IsStreamerAuth)
            {
                requestContextSettings.CachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\TwitchAssistant\Streamer";
            }
            else
            {
                requestContextSettings.CachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\TwitchAssistant\Bot";
            }
            ConnectBrowser                = new ChromiumWebBrowser();
            ConnectBrowser.MenuHandler    = new MyCustomMenuHandler();
            ConnectBrowser.RequestContext = new RequestContext(requestContextSettings);

            InitializeComponent();
            BrowserContainer.Children.Add(ConnectBrowser);
        }
 public static Context GetContext(string UUID)
 {
     if (contList.ContainsKey(UUID))
     {
         return(contList[UUID]);
     }
     else
     {
         var settings = new RequestContextSettings();
         settings.CachePath             = System.IO.Path.GetFullPath(VDB.GetSessionSavePath(UUID));
         settings.PersistSessionCookies = true;
         RequestContext reqc = new RequestContext(settings);
         reqc.LoadExtensionsFromDirectory(VDB.savepath + @"\extentions", extHandler);
         //Cef.RefreshWebPlugins();
         Context c = new Context()
         {
             context = reqc
         };
         contList.Add(UUID, c);
         return(c);
     }
 }
Exemplo n.º 29
0
        public CWB()
        {
            var browserSettings = new BrowserSettings
            {
            };
            var requestSettings = new RequestContextSettings
            {
                CachePath = @"C:\cef-cache",
            };
            var requestContext = new RequestContext(requestSettings);

            Cef.UIThreadTaskFactory.StartNew(delegate
            {
                lock (CWB.Proxies)
                {
                    if (CWB.Proxies.Any())
                    {
                        this.Proxy = CWB.Proxies.ElementAt(0);
                        CWB.Proxies.RemoveAt(0);
                        CWB.Proxies.Add(this.Proxy);

                        var dict = new Dictionary <string, object>
                        {
                            ["mode"]   = "fixed_servers",
                            ["server"] = this.Proxy,
                        };
                        var success = requestContext.SetPreference("proxy", dict, out string error);

                        if (!success || !string.IsNullOrWhiteSpace(error))
                        {
                            lock (this.Errors)
                            {
                                this.Errors.Add(error);
                            }
                        }
                    }
                }
            });
Exemplo n.º 30
0
        static async Task Main(string[] args)
        {
            Log("=================");
            Log("Starting at: {0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));

            Bitmap screenshotBitmap = null;

            var browserSettings = new BrowserSettings();

            browserSettings.WindowlessFrameRate = 5;

            var requestContextSettings = new RequestContextSettings();

            requestContextSettings.CachePath = Path.GetFullPath("cache");

            using (var requestContext = new RequestContext(requestContextSettings))
                using (var browser = new ChromiumWebBrowser(ManitobaHydroOutagesURL, browserSettings, requestContext))
                {
                    var blocker = new SemaphoreSlim(0);

                    var token = Guid.NewGuid().ToString();

                    // SignalScript doesn't seem to be working with the new embedding, which uses an IFRAME.

                    /*
                     * string SignalScript = new StreamReader(typeof(Program).Assembly.GetManifestResourceStream("CaptureHydroOutages.SignalScript.js")).ReadToEnd().Replace("TOKEN", token);
                     *
                     * browser.ConsoleMessage +=
                     *      (sender, e) =>
                     *      {
                     *              Debug.WriteLine(e.Message);
                     *
                     *              int tokenOffset = e.Message.IndexOf(token);
                     *
                     *              if (tokenOffset >= 0)
                     *              {
                     *                      Log("SIGNAL FROM SCRIPT: " + e.Message);
                     *
                     *                      string message = e.Message.Substring(tokenOffset + token.Length).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).First();
                     *
                     *                      if (message == "notready")
                     *                              Task.Delay(100).ContinueWith((task) => browser.ExecuteScriptAsyncWhenPageLoaded(SignalScript));
                     *                      else
                     *                      {
                     *                              Log("UNBLOCKING");
                     *
                     *                              blocker.Release();
                     *
                     *                              if (message == "error")
                     *                              {
                     *                                      string error = e.Message.Split(new[] { token }, StringSplitOptions.None)[1].Split('|').Last();
                     *                                      Log("ERROR FROM SCRIPT: " + error);
                     *                              }
                     *                      }
                     *              }
                     *      };
                     *
                     * browser.FrameLoadStart +=
                     *      (sender, e) =>
                     *      {
                     *              e.Frame.ExecuteJavaScriptAsync(SignalScript);
                     *      };
                     */

                    browser.Size = new Size(1920, 2000);

                    TimeSpan GracePeriodDuration = TimeSpan.FromSeconds(5);

                    var gracePeriodEnd = DateTime.UtcNow;

                    var waiter = new ManualResetEvent(initialState: false);

                    object sync = new object();

                    async void TakeScreenshot()
                    {
                        bool requireFreshRender = false;

                        Log("TakeScreenshot(): Registering for notification of the next render");

                        while (true)
                        {
                            var bitmap = await browser.ScreenshotAsync(ignoreExistingScreenshot : requireFreshRender, PopupBlending.Main);

                            requireFreshRender = true;

                            if (bitmap == null)
                            {
                                Log("TakeScreenshot(): Did not receive a bitmap from the render process");
                                break;
                            }
                            else
                            {
                                Log("TakeScreenshot(): Received bitmap from render process");

                                lock (sync)
                                {
                                    screenshotBitmap?.Dispose();
                                    screenshotBitmap = (Bitmap)bitmap.Clone();
                                }

                                gracePeriodEnd = DateTime.UtcNow + GracePeriodDuration;

                                waiter.Set();
                            }
                        }
                    }

                    /*
                     * DateTime refreshViewAfter = DateTime.UtcNow.AddSeconds(20);
                     * int refreshCount = 0;
                     *
                     * while (true)
                     * {
                     *      var remaining = refreshViewAfter - DateTime.UtcNow;
                     *
                     *      if (remaining < TimeSpan.Zero)
                     *      {
                     *              if (refreshCount >= 5)
                     *              {
                     *                      Log("ERROR: Tried refreshing {0} times, failed to receive semaphore signal from script, aborting, no image captured at {1}", refreshCount, DateTime.Now);
                     *                      Environment.Exit(1);
                     *              }
                     *
                     *              refreshCount++;
                     *
                     *              Log("WARNING: Gave up on receiving the initialization token at {0}, beginning reload attempt {1}", DateTime.Now, refreshCount);
                     *
                     *              browser.Reload();
                     *              browser.ExecuteScriptAsyncWhenPageLoaded(SignalScript);
                     *
                     *              refreshViewAfter = DateTime.UtcNow.AddSeconds(20);
                     *
                     *              continue;
                     *      }
                     *
                     *      var acquired = await blocker.WaitAsync(remaining);
                     *
                     *      if (acquired)
                     *              break;
                     * }
                     *
                     * Log("TOKEN RECEIVED, BEGINNING SCREENSHOTS, WILL WAIT UNTIL 5 SECONDS ELAPSE WITH NO SCREENSHOT");
                     */
                    Log("Waiting 20 seconds");

                    Thread.Sleep(TimeSpan.FromSeconds(20));

                    Log("Beginning screenshots");

                    TakeScreenshot();

                    await waiter.AsTask();

                    Log("WOKEN UP");

                    Bitmap capturedScreenshot = null;

                    while (true)
                    {
                        var remaining = gracePeriodEnd - DateTime.UtcNow;

                        if (remaining <= TimeSpan.Zero)
                        {
                            break;
                        }

                        Log("WAITING {0}", remaining);

                        await Task.Delay(remaining);

                        lock (sync)
                        {
                            capturedScreenshot = screenshotBitmap;
                            screenshotBitmap   = null;
                        }
                    }

                    string fileName = "screenshot-captured-" + DateTime.Now.ToString("yyyyMMdd_HHmm");

                    if (capturedScreenshot == null)
                    {
                        Log("ERROR: Did not manage to capture a screenshot");
                    }
                    else
                    {
                        /*
                         * await browser
                         *      .EvaluateScriptAsync("document.getElementsByClassName('last_updated')[0].innerText")
                         *      .ContinueWith(
                         *              (task) =>
                         *              {
                         *                      var response = task.Result;
                         *
                         *                      if (response.Success && (response.Result != null))
                         *                      {
                         *                              var formattedDateTimeString = response.Result.ToString();
                         *
                         *                              formattedDateTimeString = formattedDateTimeString.Replace("a.m.", "AM");
                         *                              formattedDateTimeString = formattedDateTimeString.Replace("p.m.", "PM");
                         *
                         *                              try
                         *                              {
                         *                                      var lastUpdatedDateTime = DateTime.ParseExact(formattedDateTimeString, format: "dddd, MMMM d 'at' h:mm tt", CultureInfo.InvariantCulture);
                         *
                         *                                      fileName += "-updated-" + lastUpdatedDateTime.ToString("yyyyMMdd_HHmm");
                         *                              }
                         *                              catch (Exception e)
                         *                              {
                         *                                      Log("ERROR: Did not manage to determine when the data set was last updated, formatted date/time string: " + formattedDateTimeString);
                         *                                      Log("=> " + e);
                         *                              }
                         *                      }
                         *                      else
                         *                              Log("ERROR: Did not manage to determine when the data set was last updated");
                         *              });
                         */

                        await browser
                        .EvaluateScriptAsync(@"
var rect = document.getElementById('outage_map_canvas').getBoundingClientRect();

rect.left += window.scrollX;
rect.top += window.scrollY;

`${rect.top},${rect.right},${rect.bottom},${rect.left}`;")
                        .ContinueWith(
                            (task) =>
                        {
                            var response = task.Result;

                            if (response.Success && (response.Result != null))
                            {
                                string rectString = response.Result.ToString();

                                Log("Received bounding rectangle: {0}", rectString);

                                string[] parts = rectString.Split(',');

                                int top    = (int)Math.Floor(double.Parse(parts[0]));
                                int right  = (int)Math.Ceiling(double.Parse(parts[1]));
                                int bottom = (int)Math.Ceiling(double.Parse(parts[2]));
                                int left   = (int)Math.Floor(double.Parse(parts[3]));

                                if ((top < bottom) && (left < right) &&
                                    (top >= 0) && (left >= 0) &&
                                    (bottom <= capturedScreenshot.Height) && (right <= capturedScreenshot.Width))
                                {
                                    Log("=> Cropping screenshot");

                                    int width  = right - left;
                                    int height = bottom - top;

                                    var cropped = new Bitmap(width, height, capturedScreenshot.PixelFormat);

                                    using (var g = Graphics.FromImage(cropped))
                                    {
                                        g.DrawImage(
                                            capturedScreenshot,
                                            destRect: new Rectangle(0, 0, width, height),
                                            srcRect: new Rectangle(left, top, width, height),
                                            srcUnit: GraphicsUnit.Pixel);
                                    }

                                    capturedScreenshot.Dispose();
                                    capturedScreenshot = cropped;
                                }
                            }
                        });
                    }

                    Log("SAVING: " + fileName);

                    capturedScreenshot.Save(fileName + ".png");
                }
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            Console.WriteLine("PulsoidRecoder バージョン0.1 (c)WSOFT 2020");
            Console.CancelKeyPress += Console_CancelKeyPress;
            CefSettings settings = new CefSettings();

            settings.Locale             = "ja";
            settings.LogSeverity        = LogSeverity.Disable;
            settings.AcceptLanguageList = "ja-JP";

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

            bool breakflag = false;

            while (!breakflag)
            {
                Console.WriteLine("PulsoidRecoder メインメニュー");
                Console.WriteLine("実行したい操作を選択してください");
                Console.Write("[R:記録モード / E:エクセル出力モード / V:閲覧モード / L:オープンソースライセンスを表示 / QまたはEsc:終了]");

                switch (Console.ReadKey().Key)
                {
                case ConsoleKey.Escape:
                {
                    breakflag = true;
                    break;
                }

                case ConsoleKey.Q:
                {
                    breakflag = true;
                    break;
                }

                case ConsoleKey.L:
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("オープンソースライセンス");
                    Console.WriteLine("PulsoidRecoderはこれらのオープンソースソフトウェアによって実現しました");
                    Console.WriteLine();
                    Console.WriteLine(PulsoidRecoder.Properties.Resources.Licences);
                    Console.WriteLine();
                    break;
                }

                case ConsoleKey.E:
                {
                    Console.WriteLine("読み込むファイル名を入力してください");
                    Console.Write("ファイルパス>");
                    string filepath = Console.ReadLine();
                    Console.Write("解析しています.");
                    BPMRecordCollection collection = LoadFile(filepath);
                    XLWorkbook          workbook   = new XLWorkbook();
                    IXLWorksheet        worksheet  = workbook.AddWorksheet();
                    worksheet.Name = "Pulseroid RecordLog";
                    IXLCell c = worksheet.Cell(1, 1);
                    c.Value = "日時";
                    IXLCell c1 = worksheet.Cell(1, 2);
                    c.Value = "心拍数";
                    IXLCell c2 = worksheet.Cell(1, 3);
                    c.Value = "最高心拍数";
                    IXLCell c3 = worksheet.Cell(1, 4);
                    c.Value = "平均心拍数";
                    IXLCell c4 = worksheet.Cell(1, 5);
                    c.Value = "最低心拍数";
                    IXLCell c5 = worksheet.Cell(2, 3);
                    c.Value = collection.Maxbpm;
                    IXLCell c6 = worksheet.Cell(2, 4);
                    c.Value = collection.Avgbpm;
                    IXLCell c7 = worksheet.Cell(2, 5);
                    c.Value = collection.Minbpm;
                    int cx    = 2;
                    int count = 0;
                    foreach (BPMRecord bpm in collection.Records)
                    {
                        IXLCell x = worksheet.Cell(cx, 1);
                        x.Value = bpm.Month + "/" + bpm.Day + " " + bpm.Hour + ":" + bpm.Minute + ":" + bpm.Second;
                        IXLCell x2 = worksheet.Cell(cx, 2);
                        x2.Value = bpm.BPM;
                        count++;
                        if (count == 60)
                        {
                            Console.Write(".");
                            count = 0;
                        }
                        cx++;
                    }
                    Console.WriteLine();
                    Console.WriteLine("解析完了");
                    Console.WriteLine("保存先を入力してください");
                    Console.Write("ファイルパス(.xlsx)>");
                    string savefilepath = Console.ReadLine();
                    if (Path.GetExtension(savefilepath) != ".xlsx")
                    {
                        savefilepath += ".xlsx";
                    }
                    Console.WriteLine("保存しています...");
                    workbook.SaveAs(savefilepath);
                    Console.WriteLine("保存完了");
                    break;
                }

                case ConsoleKey.V:
                {
                    Console.WriteLine("読み込むファイル名を入力してください");
                    Console.Write("ファイルパス>");
                    string filepath = Console.ReadLine();
                    BPMRecordCollection collection = LoadFile(filepath);
                    Console.WriteLine("記録:" + collection.Records.Length + "個 最高心拍数:" + collection.Maxbpm + "BPM 平均心拍数:" + collection.Avgbpm + "BPM 最低心拍数:" + collection.Minbpm + "BPM");
                    Console.WriteLine();
                    foreach (BPMRecord bpm in collection.Records)
                    {
                        Console.WriteLine(bpm.Month + "/" + bpm.Day + " " + bpm.Hour + ":" + bpm.Minute + ":" + bpm.Second + "  " + bpm.BPM + "BPM");
                    }
                    break;
                }

                case ConsoleKey.R:
                {
                    Console.WriteLine();
                    string WidetUrl = "";
                    Console.WriteLine("PulsoidのウィジェットUrlを入力してください");
                    Console.Write("URL>");
                    WidetUrl = Console.ReadLine();
                    int span = 1;
                    Console.WriteLine("何秒おきに記録するか設定してください");
                    Console.Write("時間(秒)>");
                    int.TryParse(Console.ReadLine(), out span);
                    if (span < 1)
                    {
                        span = 1;
                    }

                    string cachePath       = Path.GetFullPath("cache");
                    var    browserSettings = new BrowserSettings();
                    //毎秒一枚更新されればOK
                    browserSettings.WindowlessFrameRate = 1;

                    var requestContextSettings = new RequestContextSettings {
                        CachePath = cachePath
                    };


                    using (var requestContext = new RequestContext(requestContextSettings))
                        using (var browser = new ChromiumWebBrowser("", browserSettings, requestContext))
                        {
                            List <BPMRecord> records = new List <BPMRecord>();

                            //起動中は待機
                            Console.WriteLine("ブラウザを初期化しています");
                            while (!browser.IsBrowserInitialized)
                            {
                            }
                            Console.WriteLine("ページを準備しています");
                            browser.Load(WidetUrl);
                            //読み込み中は待機
                            Console.WriteLine("読み込んでいます");
                            while (browser.IsLoading)
                            {
                            }
                            Console.WriteLine("心拍表示を待機しています");
                            //BPMが表示されていない間は待機
                            while (GetBPM(browser) == 0)
                            {
                            }

                            int    maxbpm   = 0;
                            int    minbpm   = 999;
                            double bpmcount = 0;

                            int cct = Console.CursorTop;
                            int ccl = Console.CursorLeft;
                            Console.WriteLine("[***BPM  0秒]");

                            //記録スタート
                            while (true)
                            {
                                int bpm = GetBPM(browser);
                                if (maxbpm < bpm)
                                {
                                    maxbpm = bpm;
                                }
                                if (minbpm > bpm)
                                {
                                    minbpm = bpm;
                                }
                                bpmcount += bpm;
                                records.Add(new BPMRecord(DateTime.Now, bpm));
                                Task.Run(() =>
                                    {
                                        Console.SetCursorPosition(ccl, cct);
                                        Console.WriteLine("[ " + bpm + "BPM  最大:" + maxbpm + "BPM 平均:" + (int)(bpmcount / records.Count) + "BPM 最小:" + minbpm + "BPM " + records.Count + "個の記録 ]");
                                    });
                                if (preseCancel)
                                {
                                    break;
                                }
                                Thread.Sleep(span * 1000);
                            }
                            Console.WriteLine("記録を終了しました");
                            Console.WriteLine("記録の保存先を入力してください");
                            Console.Write("ファイルパス>");
                            string savepath = Console.ReadLine();
                            Console.WriteLine("保存しています...");

                            SaveFile(new BPMRecordCollection(records.ToArray(), maxbpm, minbpm, (int)(bpmcount / records.Count)), savepath);

                            Console.WriteLine("保存完了");
                        }
                    break;
                }
                }
            }
        }
Exemplo n.º 32
0
        public async Task MainAsync(GraphicsDevice gd, IntPtr windowHandle, string url, object data, System.Drawing.Size size, double zoomLevel = 1.0)
        {
            if (Browser != null)
            {
                Browser.NewFrame -= Browser_NewFrame;
                Browser.Dispose();
            }

            var browserSettings = new BrowserSettings();

            //Reduce rendering speed to one frame per second so it's easier to take screen shots
            browserSettings.WindowlessFrameRate = 30;
            var requestContextSettings = new RequestContextSettings {
                CachePath = CachePath
            };

            // RequestContext can be shared between browser instances and allows for custom settings
            // e.g. CachePath
            RequestContext = new RequestContext(requestContextSettings);
            Browser        = new MonoCefBrowser(gd, url, browserSettings, RequestContext);
            Browser.CreateBrowser(new WindowInfo()
            {
                WindowHandle = windowHandle,
                Width        = size.Width,
                Height       = size.Height,
                WindowlessRenderingEnabled = true
            }, browserSettings);
            Browser.NewFrame += Browser_NewFrame;
            Browser.Size      = size;
            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);

            await LoadPageAsync(Browser, url);

            //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();

            cefHost.SendFocusEvent(true);

            SetMarshalledData(data);

            //You can call Invalidate to redraw/refresh the image
            cefHost.Invalidate(PaintElementType.View);
        }