WPF 實現 Chrome 內核的 Webbrowser


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()

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM