Search code examples
c#androidandroid-webviewmaui.net-7.0

Modify variables by accessing android webview setting in .net maui


I found out that the viewport setting of the site displayed in the web view control of the android app developed with maui was ignored. Therefore, it is necessary to set the setUseWideViewPort setting to true in the webview control setting. But I haven't used xamarin either and maui has been used for 2 days. How can I access this setting to modify the value? https://developer.android.com/reference/android/webkit/WebSettings#setUseWideViewPort(boolean)

I found the reason for ignoring the viewport meta tag, but I don't know how to set the value not to ignore it


Solution

  • You can use Handlers to set setUseWideViewPort.

    Create a MyWebview class derived from WebView:

    namespace MauiApp1.Resources.Controls
    {
        class MyWebview:WebView
        {
        }
    }
    

    Use MyWebview in .xaml:

    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:Controls="clr-namespace:MauiApp1.Resources.Controls"
                 x:Class="MauiApp1.MainPage">
    
       <Controls:MyWebview Source="https://learn.microsoft.com/dotnet/maui"/>
    
    </ContentPage>
    

    You can then customize the WebViewHandler, via its property mapper, to perform the desired modification only to MyWebview instances:

    using MauiApp1.Resources.Controls;
    
    namespace MauiApp1;
    
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            ModifyWebview();    
        }
    
        void ModifyWebview()
        {
            Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", (Handler, View) =>
            {
                if (View is MyWebview)
                {
    #if ANDROID
                  Handler.PlatformView.Settings.UseWideViewPort= true;
    #endif
                }
            });
    
       }
    
    }