Created
April 29, 2016 10:26
-
-
Save amaitland/6cd03ad71c66e3334d505a2c79afe381 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. | |
// | |
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. | |
using System; | |
using System.Threading.Tasks; | |
using CefSharp.OffScreen; | |
namespace CefSharp.MinimalExample.OffScreen | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
const string testUrl = "https://www.google.com/"; | |
var settings = new CefSettings(); | |
// Disable GPU in WPF and Offscreen examples until #1634 has been resolved | |
settings.SetOffScreenRenderingBestPerformanceArgs(); | |
settings.WindowlessRenderingEnabled = true; | |
//Perform dependency check to make sure all relevant resources are in our output directory. | |
Cef.Initialize(settings, shutdownOnProcessExit: false, performDependencyCheck: true); | |
var result = Browser(testUrl); | |
Console.WriteLine(result); | |
// We have to wait for something, otherwise the process will exit too soon. | |
Console.ReadKey(); | |
// Clean up Chromium objects. You need to call this in your application otherwise | |
// you will get a crash when closing. | |
Cef.Shutdown(); | |
} | |
private static string Browser(string url) | |
{ | |
var task = BrowseAsync(url); | |
task.Wait(); | |
return task.Result; | |
} | |
private static async Task<string> BrowseAsync(string url) | |
{ | |
string result; | |
var browserSettings = new BrowserSettings { WindowlessFrameRate = 1 }; | |
using (var browser = new ChromiumWebBrowser(url, browserSettings)) | |
{ | |
//Wait for all resources to finish loading | |
await LoadPageAsync(browser); | |
// Wait awhile for Javascript to finish executing. | |
await Task.Delay(2000); | |
result = await browser.GetSourceAsync(); | |
//A little delay to let the browser finish doing it's thing before Disposing | |
await Task.Delay(20); | |
} | |
return result; | |
} | |
private static Task LoadPageAsync(IWebBrowser browser) | |
{ | |
var tcs = new TaskCompletionSource<bool>(); | |
EventHandler<LoadingStateChangedEventArgs> handler = null; | |
handler = (sender, args) => | |
{ | |
if (!args.IsLoading) | |
{ | |
browser.LoadingStateChanged -= handler; | |
//Call TrySetResult on the ThreadPool so any continuation is executed on the ThreadPool | |
Task.Run(delegate { tcs.TrySetResult(true); }); | |
} | |
}; | |
browser.LoadingStateChanged += handler; | |
return tcs.Task; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment