CefSharp LoadHtml

G-Man picture G-Man · Dec 26, 2014 · Viewed 25.7k times · Source

Could someone explain to me how the CefSharp LoadHtml function works?

LoadHtml(string html, string url)

What do the html and url parameters represent?

I am interested in loading a page from a raw HTML string into the CefSharp browser.

Answer

Yoshi picture Yoshi · Dec 29, 2014

Update: CefSharp has a new LoadHtml(string html) method that loads the HTML as a base64-encoded data URI. It is more reliable that the LoadHtml(string html, string url) method described below.

In LoadHtml(string html, string url):

html is your HTML string, e.g. "<html><body>Hello world</body></html>". Actually, you can even put other content in the string, such as SVG markup, as long as Chromium can understand it.

url is needed because your HTML code may contain JavaScript that tries to perform AJAX calls, and the web browser needs to understand what security restrictions apply. The scheme (e.g. "http:", "about:") and domain (e.g. "localhost", "google.com") affect behaviour such as clicking on links, AJAX requests, iframes, etc.

If you want to simply render static HTML, make the url something unique such as http://rendering/ (so that the resource handler does not overlap with a real url on the web). If you need to load the HTML and then interact with it or perform AJAX calls, choose a url that matches the domain you want to interact with - for example, if you want to make an alternative Google home page and perform AJAX search queries, you will want to use https://www.google.com/ as your URL so you can communicate with it.


You can see the source code for LoadHtml here.

What CefSharp does is:

  1. Register a resource handler for the given url.
  2. Call Load(url) to tell Chromium to load the given url.

Then, under the hood:

  1. Chromium requests the url.
  2. The resource handler intercepts the request, and returns your html.
  3. Chromium renders your html instead of the real content of the URL.