1. 使用 Nuget 添加 cefsharp.wpf 庫
2. 窗口中使用
xmlns:chrome="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf" <chrome:ChromiumWebBrowser x:Name="wbrReport"/>
3. 打開指定的 URL
// 加載 URL this.wbrReport.Address = "www.baidu.com";
4. Cefsharp.wpf 給 javascript 提供接口
1. 設置外部調用的對象
public class NtstJSObject { /// <summary> /// 提供給 Javascript 的對象 /// </summary> public static string ExportedJavascriptOjbectName = "ntst"; private ReportWindow _reportWindow = null; public NtstJSObject(ReportWindow reportWindow) { this._reportWindow = reportWindow; } /// <summary> /// 提供給 Javascript 調用的 closeWindow 接口 /// </summary> public void closeWindow() { if(this._reportWindow != null) { this._reportWindow.CloseWindow(this); } } }
2. 窗體構造函數中綁定 js 對象
// 綁定 Javascript 調用對象 CefSharpSettings.WcfEnabled = true; this.wbrReport.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true; this.wbrReport.JavascriptObjectRepository.Register(NtstJSObject.ExportedJavascriptOjbectName, new NtstJSObject(this), false, BindingOptions.DefaultBinder);
3. 窗口提供真正調用接口
/// <summary> /// Javascript 接口:closeWindow /// </summary> /// <param name="ntstJSObject"></param> public void CloseWindow(NtstJSObject ntstJSObject) { if(this._logger != null) { this._logger.WriteInformation(string.Format("Javascript call to: {0}", nameof(CloseWindow))); } this.Dispatcher.Invoke(new Action(() => { this.Close(); })); }
4. Javascript 調用方式
ntst.closeWindow()