Skip to content

Commit

Permalink
Fix BlazorWebView disposal on Android (#7349)
Browse files Browse the repository at this point in the history
  • Loading branch information
MackinnonBuck authored May 24, 2022
1 parent b041b65 commit 0ace122
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 17 deletions.
21 changes: 4 additions & 17 deletions src/BlazorWebView/src/Maui/Android/AndroidWebKitWebViewManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ internal class AndroidWebKitWebViewManager : WebViewManager
private static readonly AUri AndroidAppOriginUri = AUri.Parse(AppOrigin)!;
private readonly AWebView _webview;
private readonly string _contentRootRelativeToAppRoot;
private WebMessagePort[]? _nativeToJSPorts;

/// <summary>
/// Constructs an instance of <see cref="AndroidWebKitWebViewManager"/>.
Expand Down Expand Up @@ -74,33 +73,21 @@ internal bool TryGetResponseContentInternal(string uri, bool allowFallbackOnHost

internal void SetUpMessageChannel()
{
_nativeToJSPorts = _webview.CreateWebMessageChannel();
// These ports will be closed automatically when the webview gets disposed.
var nativeToJSPorts = _webview.CreateWebMessageChannel();

var nativeToJs = new BlazorWebMessageCallback(message =>
{
MessageReceived(AppOriginUri, message!);
});

var destPort = new[] { _nativeToJSPorts[1] };
var destPort = new[] { nativeToJSPorts[1] };

_nativeToJSPorts[0].SetWebMessageCallback(nativeToJs);
nativeToJSPorts[0].SetWebMessageCallback(nativeToJs);

_webview.PostWebMessage(new WebMessage("capturePort", destPort), AndroidAppOriginUri);
}

protected override async ValueTask DisposeAsyncCore()
{
await base.DisposeAsyncCore();

if (_nativeToJSPorts is not null)
{
foreach (var port in _nativeToJSPorts)
{
port?.Close();
}
}
}

private class BlazorWebMessageCallback : WebMessagePort.WebMessageCallback
{
private readonly Action<string?> _onMessageReceived;
Expand Down

0 comments on commit 0ace122

Please sign in to comment.