public void TakeScreenshotOffscreen(string url, string filename) { var offscreenBrowser = new CefSharp.OffScreen.ChromiumWebBrowser(); offscreenBrowser.BrowserInitialized += (o, args) => { offscreenBrowser.Load(url); offscreenBrowser.FrameLoadEnd += async(sender1, eventArgs) => { if (eventArgs.Frame.IsMain) { var sizes = await offscreenBrowser.EvaluateScriptAsync(JavascriptQueries.RequestForMaxSize); var widthAndHeight = (List <object>)sizes.Result; var screenshotSize = new System.Drawing.Size((int)widthAndHeight[0], (int)widthAndHeight[1]); offscreenBrowser.Size = screenshotSize; await Task.Delay(500); var bitmap = await offscreenBrowser.ScreenshotAsync(false, PopupBlending.Main); bitmap.Save(filename, ImageFormat.Png); offscreenBrowser.Dispose(); Process.Start(new System.Diagnostics.ProcessStartInfo { UseShellExecute = true, FileName = filename }); } }; }; }
/// <summary> /// Get a bitmap of the specified HELM in the specified size /// </summary> /// <param name="helm"></param> /// <param name="size"></param> /// <returns></returns> public Bitmap GetBitmap( string helm, Size size) { Bitmap Bitmap = null; ManualResetEvent GetBitmapEvent = new ManualResetEvent(false); Initialize(); if (Debug) { DebugLog.Message("GetBitmap Entered: " + helm + ", " + size); } Stopwatch sw = Stopwatch.StartNew(); Helm = helm; CurrentSize = size; //if (DebugMx.True) return new Bitmap(1,1); int initialOnPaintCount = OnPaintCount; // save current paint count so we can tell when page has been re-rendered with new image string script = ""; if (!String.IsNullOrWhiteSpace(helm)) { script += "jsd.setHelm(\"" + helm + "\");"; } if (!size.IsEmpty) { script += "jsd.setSize(" + size.Width + "," + size.Height + ");"; } script += "jsd.refresh();"; // redraws the structure Task <JavascriptResponse> scriptTask = OffScreenBrowser.EvaluateScriptAsync(script); // start the script async // Wait for script completion and then get the screenshot and bitmap scriptTask.ContinueWith(t => { while (OnPaintCount == initialOnPaintCount) // wait until paint event occurs that renders the new bitmap { Thread.Sleep(10); } //Thread.Sleep(2000); //Give the browser a little time to render var task = OffScreenBrowser.ScreenshotAsync(ignoreExistingScreenshot: false); // start the screenshot async, should get new bitmap // Wait for screenshot completion and get bitmap task.ContinueWith(x => { Bitmap resultBitmap = task.Result; if (!size.IsEmpty) { Rectangle section = new Rectangle(0, 0, size.Width, size.Height); section.Intersect(new Rectangle(0, 0, resultBitmap.Width, resultBitmap.Height)); // be sure section not larger than result if (section.Height > 0 && section.Width > 0) { Bitmap = resultBitmap.Clone(section, resultBitmap.PixelFormat); } else { Bitmap = new Bitmap(1, 1); // create minimal empty bitmap } } else { Bitmap = new Bitmap(resultBitmap); } // We no longer need the Bitmap. // Dispose it to avoid keeping the memory alive. Especially important in 32-bit applications. resultBitmap.Dispose(); GetBitmapEvent.Set(); }, TaskScheduler.Default); }); GetBitmapEvent.WaitOne(); // wait for the bitmap to be retrieved GetBitmapCount++; if (Debug) { DebugLog.StopwatchMessage("GetBitmap Complete, Time: ", sw); } return(Bitmap); }
/// <summary> /// Forces Special Consideration files to download immediately after they open in Adobe's chrome plugin. /// Ideally, I would disable the plugin - but for some reason doing this caused CefSharp to stall. /// If any CefSharp experts figure out a cleaner way to do this, let me know. /// </summary> /// <param name="b">The browser to inject into</param> private void specialConsiderationInject(ChromiumWebBrowser b) { string code = "document.body.innerHTML = \"<a id='d_link' href='" + current_page + "' download>Clickity</a>\"; document.querySelector('#d_link').click();"; var task = b.EvaluateScriptAsync(code); task.ContinueWith(t => { //For debug ouput when testing if (!t.IsFaulted) { //Console.WriteLine("Special Consideration @ " + current_page); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public void LoadPageSkyBet(string Url) { browser.ConsoleMessage -= BrowserOnConsoleMessage; browser.LoadingStateChanged -= BrowserOnLoadingStateChanged; browser.BrowserInitialized -= BrowserOnBrowserInitialized; browser.Delete(); browser.Dispose(); browser = new ChromiumWebBrowser(Url); browser.ConsoleMessage += BrowserOnConsoleMessage; browser.LoadingStateChanged += BrowserOnLoadingStateChanged; browser.BrowserInitialized += BrowserOnBrowserInitialized; isLoad = false; // browser.RegisterAsyncJsObject("Alljs", Properties.Resources.jsAllLoadSkybet); var alljs = Properties.Resources.jsAllLoadSkybet; var countUpdate = 0; while (true) { Thread.Sleep(200); countUpdate++; Application.DoEvents(); if (!browser.IsLoading) { if (browser.IsBrowserInitialized) { var sss = browser.EvaluateScriptAsync(alljs).Result; var result = browser.EvaluateScriptAsync("checkLoad()").Result; if ((result.Result != null) && ((bool) result.Result == true)) { var ss = browser.EvaluateScriptAsync(alljs).Result; break; } } } if (countUpdate > 30) { if (browser.IsBrowserInitialized) browser.Delete(); browser.Dispose(); browser = Chrome.InitSkyBet(Url); browser.ConsoleMessage += BrowserOnConsoleMessage; browser.LoadingStateChanged += BrowserOnLoadingStateChanged; browser.BrowserInitialized += BrowserOnBrowserInitialized; isLoad = false; countUpdate = 0; } } }
public static int BrowserWidth(ChromiumWebBrowser b) { // Get Document Height var task = b.EvaluateScriptAsync("(function() { var body = document.body, html = document.documentElement; return Math.max( body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth ); })();"); task.ContinueWith(t => { if (!t.IsFaulted) { var response = t.Result; var EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message; //MessageBox.Show(response.Result.ToString()); //MessageBox.Show(EvaluateJavaScriptResult.ToString()); } }); if (task.Result.Result == null) { return 0; } return Convert.ToInt32(task.Result.Result.ToString()); }
/// <summary> /// Injects the Javascript code and processes the result. /// </summary> /// <param name="b">The ChromimumWebBrowser to inject into.</param> private void Inject(ChromiumWebBrowser b) { if (!emergency_stop) { //All clear. 99.99% of the time the above doesn't matter. var task = b.EvaluateScriptAsync(js_inject); task.ContinueWith(t => { if (!t.IsFaulted) { var response = t.Result; if (response.Success == true && response.Result != null) { var result = response.Result.ToString(); if (result != string.Empty && result != "null" && result != "login successful" && result != "login unsuccessful") { potentialLoginFails = 0; //No need to worry :-) OnLoginSuccess?.Invoke(new object(), new EventArgs()); //Tell the main class it's all good Dictionary<string, string> conversion = JsonConvert.DeserializeObject<Dictionary<string, string>>(result); foreach (var pair in conversion) { int dummy = 0; if (int.TryParse(pair.Key, out dummy)) { urls.Add(new CrawlableURL(current_unitcode, pair.Value)); //Console.WriteLine("[* Discovered] [" + current_unitcode + "] " + pair.Value); } else { string u_code = pair.Key.Substring(0, 6); urls.Add(new CrawlableURL(u_code, pair.Value)); Unit.EnsureExists(new Unit(u_code, pair.Value)); //Console.WriteLine("[* Discovered] [" + pair.Key.Substring(0, 6) + "] " + pair.Value); } } if (urls.Count > 0) { if (OnCrawlingEvent != null) OnCrawlingEvent(new object(), new EventArgs()); Continue(); } } else if (result == "login successful" || result == "login unsuccessful") { ++potentialLoginFails; if (potentialLoginFails > potentialLoginFailsThreshold) { //We might have a problem xD emergency_stop = true; b_root.Load("local"); //Park until everything is sorted out. potentialLoginFails = 0; if (OnLoginProblem != null) OnLoginProblem(new object(), new EventArgs()); } } } } }, TaskScheduler.FromCurrentSynchronizationContext()); } }