This was not an easy one, I've been working on this for that last 3 days but finally got it working.
What you'll need:
- Custom WebViewClient
- Custom MauiBlazorWebViewHandler
Under platforms => Android, add your custom WebViewClient, this will be a deravitave of WebViewClient but to maintain Blazor functionality will also take the current/existing WebViewClient as a parameter which will be used where necessary. In the ShouldOverrideUrlLoading we will load the original url but we will pass additional headers and finish of the method with calling the original client's method.
public class CustomAndroidWebViewClient: WebViewClient
{
private readonly WebViewClient _client;
public CustomAndroidWebViewClient(WebViewClient client)
{
_client = client;
_deviceId = deviceId;
}
public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest request)
{
return _client.ShouldInterceptRequest(view, request);
}
public override bool ShouldOverrideUrlLoading(WebView? view, IWebResourceRequest? request)
{
view.LoadUrl(request.Url.ToString(), new Dictionary<string, string>() { { "MyHeader", "HeaderValue" } });
return _client.ShouldOverrideUrlLoading(view, request);
}
public override void OnPageFinished(WebView? view, string? url)
=> _client.OnPageFinished(view, url);
protected override void Dispose(bool disposing)
{
if (!disposing)
return;
_client.Dispose();
}
}
Next will be the custom MauiBlazorWebViewHandler, this will replace the default handler of the BlazorWebView and will replace the base WebViewClient with our custom WebViewClient and will inherit from the default BlazorWebViewHandler. This can be placed in the root space of your application or in a specific folder.
public sealed partial class MauiBlazorWebViewHandler : BlazorWebViewHandler
{
public MauiBlazorWebViewHandler()
{
}
public override void SetMauiContext(IMauiContext mauiContext)
{
base.SetMauiContext(mauiContext);
}
protected override void ConnectHandler(WebView platformView)
{
base.ConnectHandler(platformView);
platformView.Settings.JavaScriptEnabled = true;
platformView.SetWebViewClient(
new CustomAndroidWebViewClient(platformView.WebViewClient));
}
}
To make it all work, in MauiProgram.cs add:
#if ANDROID
builder.ConfigureMauiHandlers(handlers => {
handlers.AddHandler<IBlazorWebView, MauiBlazorWebViewHandler>();
});
#endif
NOTE: I'm using a #if ANDROID block because i've only implemented this handler for Android and do not need any of this functionality on other platforms.