Requesting location and notification permissions in a webview

giulichajari

Member
Joined
Nov 6, 2024
Messages
7
Programming Experience
1-3
This is the code of my webView Class, i already achieve requesting Camera Permisions for the webView, but geolocation and push notification are not working:

MyWebChormeClient.cs:
public static class MauiAppServices
{
    public static async Task<bool> CheckAndRequestCameraPermission()
    {
        var status = await Permissions.CheckStatusAsync<Permissions.Camera>();
        if (status != PermissionStatus.Granted)
        {
            status = await Permissions.RequestAsync<Permissions.Camera>();
        }

        return status == PermissionStatus.Granted;
    }
    public static async Task<bool> CheckAndRequestLocationPermission()
    {
        var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
        if (status != PermissionStatus.Granted)
        {
            status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
        }

        return status == PermissionStatus.Granted;
    }

    public static async Task<bool> CheckAndRequestNotificationPermission()
    {
        if (OperatingSystem.IsAndroidVersionAtLeast(33))
        {
            var status = await Permissions.CheckStatusAsync<Permissions.PostNotifications>();
            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.PostNotifications>();
            }

            return status == PermissionStatus.Granted;
        }

        // Si la versión de Android no requiere permiso explícito, lo damos por concedido.
        return true;
    }
}
public class MyWebChromeClient : WebChromeClient
{
    public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
    {
        if (filePathCallback is null)
            return base.OnShowFileChooser(webView, filePathCallback, fileChooserParams);

        OnShowFileChooserAsync(filePathCallback, fileChooserParams).Wait();

        return true;
    }
    public override void OnPermissionRequest(PermissionRequest request)
    {
        var resources = request.GetResources();

        // Comprueba si la solicitud incluye acceso a recursos comunes (video, audio, o ubicación)
        if (resources.Contains(PermissionRequest.ResourceVideoCapture) ||
            resources.Contains(PermissionRequest.ResourceAudioCapture))
        {
            request.Grant(resources); // Otorga permisos automáticamente para recursos de video/audio
        }
        else if (resources.Contains("android.webkit.resource.GEOLOCATION"))
        {
            // Verifica si el permiso de ubicación está otorgado
            Task.Run(async () =>
            {
                var hasLocationPermission = await MauiAppServices.CheckAndRequestLocationPermission();
                if (hasLocationPermission)
                {
                    request.Grant(resources); // Otorga el permiso de geolocalización
                }
                else
                {
                    request.Deny();
                }
            });
        }
        else
        {
            base.OnPermissionRequest(request);
        }
    }
    
    ....
    }

The App on Android request the user for geolocation but webView don't take the coordinates and dont receive notifications.
 
While running your debugger, when you set breakpoint on lines 18, 31, and 67, do you hit the breakpoints?
 
i achieve using geolocation using the code below:
C#:
    public override void OnGeolocationPermissionsShowPrompt(string? origin, GeolocationPermissions.ICallback? callback)
    {
        if (callback == null)
            return;

        MainThread.BeginInvokeOnMainThread(async () =>
        {
            // Verificar y solicitar permisos
            var permissionStatus = await MauiAppServices.CheckAndRequestLocationPermission();

            // Invocar el callback con el resultado del permiso
            callback.Invoke(origin, permissionStatus, false);
        });
    }

Now i'm going to try the debug at the lines you had told me.
 
Are lines 26 and 28 even reached?
 
Are lines 26 and 28 even reached?

it never enter to the function for asking for permissions, that my contentpage with the webview:
C#:
        public RepoWeb()
        {
            InitializeComponent();

#if ANDROID
            webView.HandlerChanged += (s, e) =>
            {
                if (webView.Handler.PlatformView is Android.Webkit.WebView androidWebView)
                {
                    androidWebView.Settings.JavaScriptEnabled = true;
                    androidWebView.Settings.MediaPlaybackRequiresUserGesture = false;
                    androidWebView.Settings.AllowFileAccess = true;
                    androidWebView.Settings.AllowContentAccess = true;

                    // Configuración de WebChromeClient para manejar permisos de la cámara
                   androidWebView.SetWebChromeClient(new MyWebChromeClient());
                  


                }
            };
            
                  
#endif
            webView.Navigated += OnNavigated;
            Loaded += ContentPage_Loaded;

        }
 
Back
Top Bottom