Embedding a browser with Cefsharp in WPF
In daily development, we need to embed some Web pages in the desktop client software. Below we use Cefsharp embedded browser to implement.
First introduce the Cefsharp embedded browser, which is based on a Google browser component, we can use it in the Wpf/winform client software. Cefsharp code is hosted on GitHub,. NET (WPF and Windows Forms) bindings for the Chromium Embedded Framework.
Currently the latest version of Cefsharp is version 41.0, if your client software needs to support the Win XP operating system, it is recommended to use CEFSHARP.WPF 1.25.7 and previous versions . You can get specific content from NuGet. In the new version of Cefsharp, support for the Win XP system has been canceled.
Specific implementation: (The first reference Cefsharp.dll,cefsharp.wpf.dll in addition to the Icudt.dll,libcef.dll two DLLs placed in the Bin/debug or bin/release directory )
First create a UserControl, and inherit the IRequestHandler interface, the code is as follows:
Ui:
<usercontrol x:class= "Embeddedwebbrowsersolution.webpageviewer" xmlns= "http://schemas.microsoft.com/ Winfx/2006/xaml/presentation " xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml " xmlns:mc="/http/ schemas.openxmlformats.org/markup-compatibility/2006 " xmlns:d=" http://schemas.microsoft.com/expression/ blend/2008 " xmlns:local=" clr-namespace:embeddedwebbrowsersolution " xmlns:uc=" Clr-namespace: Embeddedwebbrowsersolution " mc:ignorable=" D " d:designheight=" "d:designwidth=" > <grid X : Name= "Maingrid" > <uc:maskloading x:name= "maskloading"/> </Grid></UserControl>
Code:
Public partial class Webpageviewer:usercontrol, IRequestHandler {private WebView _view; Public webpageviewer (string url) {initializecomponent (); Cef. Initialize (new Settings {logseverity = logseverity.disable, packloadingdisabled = true}); Browsersettings browsersetting = new Browsersettings {applicationcachedisabled = true, pagecachedisabled = true}; _view = new WebView (string. Empty, browsersetting) {Address = URL, RequestHandler = this, Bac Kground = Brushes.white}; _view. loadcompleted + = _view_loadcompleted; MainGrid.Children.Insert (0, _view); } private void _view_loadcompleted (object sender, Loadcompletedeventargs URL) {Dispatcher.begini Nvoke (new Action () = {maskloading.visibility = visibility.collapsed; })); } public void View (STRing URL) {if (_view. isbrowserinitialized) {_view. Visibility = Visibility.hidden; maskloading.visibility = visibility.visible; _view. Load (URL); }} #region IRequestHandler public bool Getauthcredentials (Iwebbrowser browser, bool IsProxy, string Host, int port, string realm, string scheme, ref string username, ref string password) {return false; } public bool Getdownloadhandler (Iwebbrowser Browser, string mimeType, String fileName, long contentlength, R EF Idownloadhandler handler) {return true; } public bool Onbeforebrowse (Iwebbrowser Browser, irequest request, Navigationtype Naigationvtype, bool isredirect) {return false; } public bool Onbeforeresourceload (Iwebbrowser Browser, Irequestresponse requestresponse) {retur n false; } public void OnresourcereSponse (iwebbrowser Browser, string url, int status, String statustext, String mimeType, WebHeaderCollection headers) {} #endregion}
Next, carry it on the MainWindow,
Ui:
<Grid> <DockPanel> <stackpanel dockpanel.dock= "Top" orientation= "Horizontal" > < TextBlock text= "Address:" margin= "5"/> <textbox x:name= "txtaddress" width= "" margin= "5"/> < Button content= "Go" margin= "5" click= "Ongoclick" isdefault= "True"/> </StackPanel> <grid x:name= "Maingrid" > </Grid> </DockPanel> </Grid>
Code:
private void Ongoclick (object sender, RoutedEventArgs e) { string url = txtaddress.text; if (!string. Isnullorwhitespace (URL)) { Webpageviewer viewer = new Webpageviewer (URL); MainGrid.Children.Insert (0,viewer); } }
Note that you need to set the project platform target to X86.
Operating effect:
Here, an example of using Cefsharp to host Web pages is done.
Compared to WPF built-in Webbrowser,cefsharp in the processing of JS back, more convenient than WebBrowser. Take a look at the following example:
We have such an HTML page:
<! DOCTYPE html>callbackobj.showmessage (' Message from JS '); } </script>
Add a class called: Callbackobjectforjs
public class Callbackobjectforjs { showmessage(String msg) { MessageBox.Show (msg); } }
Note the name of this method must be lowercase.
Transform the Webpageviewer class, after the construction webview, register a JS object,
//... Public webpageviewer (string url) { InitializeComponent (); Cef. Initialize (new Settings {logseverity = logseverity.disable, packloadingdisabled = true}); Browsersettings browsersetting = new Browsersettings {applicationcachedisabled = true, pagecachedisabled = true}; _view = new WebView (string. Empty, browsersetting) { Address = URL, requesthandler = this, Background = Brushes.white }; _view. Registerjsobject ("Callbackobj", New Callbackobjectforjs ()); _view. loadcompleted + = _view_loadcompleted; MainGrid.Children.Insert (0, _view); } //...
The results are as follows:
In this way, we can well implement the interaction between the Web page and the client program. Click here to download the code.
Thank you for reading!
Using CEFSHARP to embed a browser in WPF (GO)