Skip to content

Commit

Permalink
feat: Support for WebMessageReceived on iOS/macOS
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinZikmund committed Apr 7, 2023
1 parent 3f56543 commit cb09425
Showing 1 changed file with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@

namespace Windows.UI.Xaml.Controls;

public partial class UnoWKWebView : WKWebView, INativeWebView
public partial class UnoWKWebView : WKWebView, INativeWebView, IWKScriptMessageHandler
#if __MACOS__
,IHasSizeThatFits
#endif
{
private CoreWebView2 _coreWebView;
private bool _isCancelling;

private const string WebMessageHandlerName = "unoWebView";
private const string OkResourceKey = "WebView_Ok";
private const string CancelResourceKey = "WebView_Cancel";

Expand All @@ -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";
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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());
}
}
}

0 comments on commit cb09425

Please sign in to comment.