Monthly Archives

Leden 2015

LoadHtml in CefSharp3

By | Programming, Winforms | No Comments

CefSharp allows you to server an in-app html page via LoadHtml method. Unfortunately all tries serving app related content via this method resulted into blank page. LoadHtml seems to be too inevitable method to load a html content into CefSharp. The only way to make it working as requested is to register a classes derived from ISchemeHandler, ISchemeHandlerFactory (CefSharp sample does it as well).

CustomSchemeHandler class derived from ISchemeHandler

internal class CustomSchemeHandler : ISchemeHandler
    {
        private readonly IDictionary<string, string> resources;
 
        public CustomSchemeHandler()
        {
            resources = new Dictionary<string, string>
            {
                { "/page", Resources.inapppage},
            };
        }
 
        public bool ProcessRequestAsync(IRequest request, ISchemeHandlerResponse response, OnRequestCompletedHandler requestCompletedCallback)
        {
            // The 'host' portion is entirely ignored by this scheme handler.
            var uri = new Uri(request.Url);
            var fileName = uri.AbsolutePath;
 
            string resource;
            if (resources.TryGetValue(fileName, out resource) &&
                !String.IsNullOrEmpty(resource))
            {
                var bytes = Encoding.UTF8.GetBytes(resource);
                response.ResponseStream = new MemoryStream(bytes);
                response.MimeType = GetMimeType(fileName);
                requestCompletedCallback();
 
                return true;
            }
 
            return false;
        }
 
        private string GetMimeType(string fileName)
        {
            if (fileName.EndsWith(".css")) return "text/css";
            if (fileName.EndsWith(".js")) return "text/javascript";
 
            return "text/html";
        }
    }

CustomSchemeHandlerFactory class derived from ISchemeHandlerFactory

    internal class CustomSchemeHandlerFactory : ISchemeHandlerFactory
    {
        public const string SchemeName = "custom";
 
        public ISchemeHandler Create()
        {
            return new CustomSchemeHandler();
        }
    }

Initialization of CustomSchemeHandlerFactory

var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
    SchemeName = CustomSchemeHandlerFactory.SchemeName,
    SchemeHandlerFactory = new CustomSchemeHandlerFactory()
});
Cef.Initialize(settings);

To access the in-app html page chnage browser.Address = „custom://test/Page“.