user461051 user461051 - 3 months ago 124
C# Question

Working with locally built web page in CefSharp

I have a CefSharp browser created in my Winform and I need to dynamically build an HTML page in memory and then have CefSharp render it.

Ideally I would like to pass the constructor a string with the HTML in it but it is expecting a URL. The answer is probably no, but is there a directive you can prepend the string with to let CefSharp know it is a string that contains a web page? Then CefSharp will create a temp file?

If not, where is the Chromium temp folder set to? Will it work if I write a file to there and then pass that as a fully qualified path? I know Chrome will support something like file:///Users/dmacdonald/Documents/myFile.htm as a URL but not sure how to form a URL if using the temp structure.

Here is my new code but my browser object doesn't have a ResourceHandler property. I see it has a ResourceHandlerFactory

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp.WinForms;
using CefSharp;


namespace DanCefWinForm
{
public partial class Form1 : Form
{
public const string TestResourceUrl = "http://maps/resource/load";

public Form1()
{
InitializeComponent();


}

private void Form1_Load(object sender, EventArgs e)
{
ChromiumWebBrowser browser = new ChromiumWebBrowser("http://maps/resource/load")
{
Dock = DockStyle.Fill,
};

var handler = browser.ResourceHandler;

browser.Location = new Point(20, 20);
browser.Size = new Size(100, 100);
this.Controls.Add(browser);
}
}
}

Answer

See https://github.com/cefsharp/CefSharp/blob/v39.0.0-pre02/CefSharp.Example/CefExample.cs#L44 for an example of registering a ResourceHandler for an in-memory string.

As you can see, it still has an URL (web resources generally tend to have that) but it can be a dummy one of your choice.

Here's the GitHub search for how it's called in the WinForms (and WPF) example apps: https://github.com/cefsharp/CefSharp/search?utf8=%E2%9C%93&q=RegisterTestResources

Another, probably less favourable, option with a temp file (anywhere?) in the local file system is to use FileAccessFromFileUrlsAllowed