CefSharp LoadHtml
有人可以向我解释一下 CefSharp
1 | LoadHtml(string html, string url) |
我有兴趣将原始 HTML 字符串中的页面加载到 CefSharp 浏览器中。
Update: CefSharp has a new
LoadHtml(string html) method that loads the HTML as a base64-encoded data URI. It is more reliable that theLoadHtml(string html, string url) method described below.
在
如果您想简单地呈现静态 HTML,请将
您可以在此处查看
CefSharp 所做的是:
然后,在引擎盖下:
试试下面的代码
1 2 3 4 5 6 7 8 9 10 11 | Cef.Initialize(new CefSettings()); ChromiumWebBrowser browser = new ChromiumWebBrowser(string.Empty) { Location = new Point(0, 0), Dock = DockStyle.Fill }; //add to a System.Windows.Forms.Form or some other container. this.Controls.Add(browser); //the url parameter does not have to be an existing address. browser.LoadHtml("<html><head></head><body>Hello, World!</body></html>","http://www.example.com/"); |
希望这有帮助。
对于 WPF 项目,请尝试以下操作。
在 xaml 中创建对 CefSharp.Wpf 的命名空间引用。
xmlns:cef="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
将 ChromiumWebBrowser 元素添加到您的窗口中。
1 | <cef:ChromiumWebBrowser x:Name="browser" IsBrowserInitializedChanged="browser_IsBrowserInitializedChanged"></cef:ChromiumWebBrowser> |
请记住为元素指定一个名称(在本例中,该元素称为浏览器)。稍后我们将使用它来调用 LoadHtml 方法。
为 IsBrowserInitializedChanged 事件创建一个事件处理程序。这很重要,因为一旦 ChromiumWebBrowser 控件准备就绪,就会触发此事件。然后我们可以加载 html.
把它们放在一起......
主窗口.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 | <Window x:Class="CEF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:CEF" xmlns:cef="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid> <cef:ChromiumWebBrowser x:Name="browser" IsBrowserInitializedChanged="browser_IsBrowserInitializedChanged"></cef:ChromiumWebBrowser> </Grid> </Window> |
主窗口.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System.Windows; namespace CEF { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void browser_IsBrowserInitializedChanged(object sender, DependencyPropertyChangedEventArgs e) { // the browser control is initialized, now load the html browser.LoadHtml("<html><head></head><body>Hello, World!</body></html>","http://www.example.com/"); } } } |