How to set custom WebViewClient on Android handler

jw 1 Reputation point
2022-08-15T15:25:47.37+00:00

I am working on brand new Maui app, and would like to know how I can use a custom WebViewClient on Android, using MAUI handlers.
I have tried the AppendToMapping, or PrependToMapping but couldn't get it working without fully overriding the handler.

Can somebody point me in the right direction wit a sample?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,231 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 29,381 Reputation points Microsoft Vendor
    2022-08-16T09:33:41.013+00:00

    Hello @jw ,

    You can follow the steps below:

    Register the handler using the AddHandler method in the MauiProgram class

      builder.UseMauiApp<App>().ConfigureMauiHandlers(Handlers =>  
                 {  
         #if __ANDROID__  
                    Handlers.AddHandler(typeof(MyCustomWebView), typeof(MyCustomWebViewHandler));// MyCustomWebView should be your webview  
         #endif  
                 });  
    

    Override the CreatePlatformView method that renders the platform control in MyCustomWebViewHandler class, and you can call SetWebViewClient method to set the WebViewClient

      partial class MyCustomWebViewHandler: WebViewHandler  
         {  
             protected override Android.Webkit.WebView CreatePlatformView()  
             {  
                 Android.Webkit.WebView customWebView =  new Android.Webkit.WebView(Android.App.Application.Context);  
                 customWebView.SetWebViewClient(new MyCustomWebClient());//your WebViewClient   
                customWebView.SetWebChromeClient(new MyCustomWebChomeClient());// your WebChomeClient  
                 return customWebView;  
             }  
         }  
    

    For more details , refer to .NET MAUI control customization with handlers - .NET MAUI | Microsoft Learn and Porting Custom Renderers to Handlers in Wiki

    Best Regards,
    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.