From cb0942550ab2d5f682ac7a466dc5481d299ad20b Mon Sep 17 00:00:00 2001 From: Martin Zikmund Date: Thu, 30 Mar 2023 12:17:51 +0200 Subject: [PATCH] feat: Support for WebMessageReceived on iOS/macOS --- .../Native/iOSmacOS/UnoWKWebView.iOSmacOS.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/Uno.UI/UI/Xaml/Controls/WebView/Native/iOSmacOS/UnoWKWebView.iOSmacOS.cs b/src/Uno.UI/UI/Xaml/Controls/WebView/Native/iOSmacOS/UnoWKWebView.iOSmacOS.cs index 39622aa30cf1..6004ffaf02dc 100644 --- a/src/Uno.UI/UI/Xaml/Controls/WebView/Native/iOSmacOS/UnoWKWebView.iOSmacOS.cs +++ b/src/Uno.UI/UI/Xaml/Controls/WebView/Native/iOSmacOS/UnoWKWebView.iOSmacOS.cs @@ -27,7 +27,7 @@ namespace Windows.UI.Xaml.Controls; -public partial class UnoWKWebView : WKWebView, INativeWebView +public partial class UnoWKWebView : WKWebView, INativeWebView, IWKScriptMessageHandler #if __MACOS__ ,IHasSizeThatFits #endif @@ -35,6 +35,7 @@ public partial class UnoWKWebView : WKWebView, INativeWebView private CoreWebView2 _coreWebView; private bool _isCancelling; + private const string WebMessageHandlerName = "unoWebView"; private const string OkResourceKey = "WebView_Ok"; private const string CancelResourceKey = "WebView_Cancel"; @@ -59,6 +60,8 @@ public partial class UnoWKWebView : WKWebView, INativeWebView } } + Configuration.UserContentController.AddScriptMessageHandler(this, WebMessageHandlerName); + // Set strings with fallback to default English OkString = !string.IsNullOrEmpty(ok) ? ok : "OK"; CancelString = !string.IsNullOrEmpty(cancel) ? cancel : "Cancel"; @@ -383,8 +386,8 @@ internal bool OnStarted(Uri targetUrl, bool stopLoadingOnCanceled = true) _isCancelling = false; _coreWebView.RaiseNavigationStarting(CoreWebView2.BlankUrl, out var cancel); //TODO:MZ: For HTML content var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(htmlContent); - //var base64String = System.Convert.ToBase64String(plainTextBytes); - //var htmlUri = new Uri(string.Format(CultureInfo.InvariantCulture, DataUriFormatString, base64String)); + //var base64String = System.Convert.ToBase64String(plainTextBytes); + //var htmlUri = new Uri(string.Format(CultureInfo.InvariantCulture, DataUriFormatString, base64String)); if (cancel) { @@ -595,4 +598,11 @@ private static string GetBestFolderPath(Uri fileUri) } } + public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message) + { + if (message.Name == WebMessageHandlerName) + { + _coreWebView.RaiseWebMessageReceived((message.Body as NSString)?.ToString()); + } + } }