Skip to content

Instantly share code, notes, and snippets.

@amaitland
Created August 4, 2015 11:48
Show Gist options
  • Save amaitland/7cb77867e45db4aff00b to your computer and use it in GitHub Desktop.
Save amaitland/7cb77867e45db4aff00b to your computer and use it in GitHub Desktop.
// 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.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace CefSharp.OffScreen.Example
{
public class Program
{
private const string TestUrl = "http://livechatinc.com/";
public static void Main(string[] args)
{
Console.WriteLine("This example application will load {0}, take a screenshot, and save it to your desktop.", TestUrl);
Console.WriteLine("You may see a lot of Chromium debugging output, please wait...");
Console.WriteLine();
var settings = new CefSettings
{
LogSeverity = LogSeverity.Disable
};
settings.UserAgent += "MyBeautifulUserAgent";
Cef.Initialize(settings);
MainAsync("cachePath1", 1.0);
//Demo showing Zoom Level of 3.0
//Using seperate request contexts allows the urls from the same domain to have independent zoom levels
//otherwise they would be the same - default behaviour of Chromium
//MainAsync("cachePath2", 3.0);
// 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 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))
{
browser.RequestHandler = new MyBeautifulRequestHandler();
browser.ConsoleMessage += browser_ConsoleMessage;
browser.StatusMessage += browser_StatusMessage;
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 void browser_ConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
Console.WriteLine("============================================================================");
Console.WriteLine("[" + e.Source + "][" + e.Line + "]" + e.Message);
Console.WriteLine("============================================================================");
}
static void browser_StatusMessage(object sender, StatusMessageEventArgs e)
{
Console.WriteLine("============================================================================");
Console.WriteLine(e.Value);
Console.WriteLine("============================================================================");
}
public static Task LoadPageAsync(IWebBrowser browser, string address = null)
{
var tcs = new TaskCompletionSource<bool>();
EventHandler<LoadingStateChangedEventArgs> handler = null;
handler = (sender, args) =>
{
//Wait for while page to finish loading not just the first frame
if (!args.IsLoading)
{
browser.LoadingStateChanged -= handler;
tcs.TrySetResult(true);
}
};
browser.LoadingStateChanged += handler;
if (!string.IsNullOrEmpty(address))
{
browser.Load(address);
}
return tcs.Task;
}
private static void DisplayBitmap(Task<Bitmap> task)
{
// Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png)
var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png");
Console.WriteLine();
Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
var bitmap = task.Result;
// Save the Bitmap to the path.
// The image type is auto-detected via the ".png" extension.
bitmap.Save(screenshotPath);
// We no longer need the Bitmap.
// Dispose it to avoid keeping the memory alive. Especially important in 32-bit applications.
bitmap.Dispose();
Console.WriteLine("Screenshot saved. Launching your default image viewer...");
// Tell Windows to launch the saved image.
Process.Start(screenshotPath);
Console.WriteLine("Image viewer launched. Press any key to exit.");
}
}
public class MyBeautifulRequestHandler : IRequestHandler
{
public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
{
return false;
}
public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, IRequestCallback callback)
{
return true;
}
public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
{
Console.WriteLine("Not interested in this one");
}
public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
Console.Write(request.Url);
Task.Run(delegate
{
try
{
var webRequest = WebRequest.Create(request.Url);
webRequest.Method = "HEAD";
webRequest.Proxy = null;
webRequest.Timeout = 5000;
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse.ContentLength != -1)
{
Console.Write(":" + webResponse.ContentLength);
}
}
}
catch (Exception ex)
{
Console.Write(":EX=" + ex.Message);
}
Console.WriteLine(":Done");
callback.Continue(true);
});
return CefReturnValue.ContinueAsync;
}
public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
return false;
}
public bool OnBeforePluginLoad(IWebBrowser browserControl, IBrowser browser, string url, string policyUrl, WebPluginInfo info)
{
return false;
}
public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
{
Console.WriteLine("Render process terminated");
}
public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
{
callback.Continue(true);
return false;
}
public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
{
Console.WriteLine("OnResourceRedirect");
}
public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
{
return true;
}
public void OnFaviconUrlChange(IWebBrowser browserControl, IBrowser browser, IList<string> urls)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment