From 51371ab2cf18506909ffb0e6de5e51dd6195c720 Mon Sep 17 00:00:00 2001 From: zhangyazhou Date: Sun, 11 Dec 2022 20:29:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0js=20=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MainWindow.xaml.cs | 63 ++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/CefSharp.MinimalExample.Wpf/MainWindow.xaml.cs b/CefSharp.MinimalExample.Wpf/MainWindow.xaml.cs index 7310db4..f373886 100644 --- a/CefSharp.MinimalExample.Wpf/MainWindow.xaml.cs +++ b/CefSharp.MinimalExample.Wpf/MainWindow.xaml.cs @@ -1,4 +1,12 @@ -using System.Windows; +using System; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Input; +using CefSharp.Event; +using CefSharp.JavascriptBinding; +using CefSharp.Wpf; +using CefSharp.Wpf.Experimental; +using CefSharp.Wpf.Internals; namespace CefSharp.MinimalExample.Wpf { @@ -7,8 +15,23 @@ namespace CefSharp.MinimalExample.Wpf public MainWindow() { InitializeComponent(); + Browser.BrowserSettings.Javascript = CefState.Enabled; + Browser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true; Browser.FrameLoadStart += BrowserOnFrameLoadStart; Browser.FrameLoadEnd += BrowserOnFrameLoadEnd; + Browser.JavascriptObjectRepository.Register("script", new Script(), false, BindingOptions.DefaultBinder); + // Browser.JavascriptObjectRepository.ResolveObject += JavascriptObjectRepositoryOnResolveObject; + Browser.WpfKeyboardHandler = new WebBrowserWpfKeyboardHandler(Browser); + } + + private void JavascriptObjectRepositoryOnResolveObject(object sender, JavascriptBindingEventArgs e) + { + var repo = e.ObjectRepository; + if (e.ObjectName == "script") + { + repo.NameConverter = new CamelCaseJavascriptNameConverter(); + repo.Register("script", new Script(), isAsync: true, options: BindingOptions.DefaultBinder); + } } private void BrowserOnFrameLoadEnd(object sender, FrameLoadEndEventArgs e) @@ -65,5 +88,43 @@ namespace CefSharp.MinimalExample.Wpf JsResultTb.Text = "js is empty!"; } } + + public string GetWindowName() + { + return "MainWindow"; + } + + public void printLog(string log) + { + Console.WriteLine($"printLog:{log}"); + } + } + + public class WebBrowserWpfKeyboardHandler : WpfImeKeyboardHandler + { + public WebBrowserWpfKeyboardHandler(ChromiumWebBrowser owner) : base(owner) + { + } + public override void HandleKeyPress(KeyEventArgs e) + { + base.HandleKeyPress(e); + if (e.Key == Key.F12) + { + owner.ShowDevTools(); + } + } + } + + public class Script + { + public string GetWindowName() + { + return "MainWindow"; + } + + public void PrintLog(string log) + { + Console.WriteLine($"H5 log:{log}"); + } } }