MAUI WebView access geolocation

Andy 45 Reputation points
2023-12-10T17:36:51.0566667+00:00

On my .NET MAUI project (Android) I'm using a WebView to access a webpage, which does ask for location permission. I've already added native location permission to my app, which does ask when I start it. But when the webpage tries to access the location, I always get

User denied the request for Geolocation

It seems that I have to add the location permission to the WebView itself? If so, how do I achieve this?

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

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 69,386 Reputation points Microsoft Vendor
    2023-12-11T06:42:31.97+00:00

    Hello,

    ==================Update=================

    When the webpage loaded and I want to access location on the webpage, nothing happens, I still get the "User denied the request for Geolocation" message. The OnGeolocationPermissionsShowPrompt Handler does never fire.

    You can move the CheckAndRequestLocationPermission method to the webview hander, after user grand this location permission, refresh this webview in the MainThread.

       Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", async (handler, view) =>
                {
    #if ANDROID
                    handler.PlatformView.Settings.SetGeolocationEnabled(true);
                    handler.PlatformView.Settings.JavaScriptCanOpenWindowsAutomatically = true;
                    handler.PlatformView.Settings.JavaScriptEnabled = true;
                    handler.PlatformView.SetWebChromeClient(new MyWebChromeClient());
                    await CheckAndRequestLocationPermission().ContinueWith(action =>
                    {
                        //After user grand this location permission, refresh this webview.
                        MainThread.BeginInvokeOnMainThread(() => {
                            view.Reload();
                        });
                      
                    });
    #endif
                });
    

    It seems that I have to add the location permission to the WebView itself? If so, how do I achieve this?

    Yes.

    Firstly, you need to add these permissions to your AndroidManifest.xaml

    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    Then, please add handler for your webview to enable the Geolocation, JS and rewrite webChromeClient. By the way, You can add this handler to webview's layout background code.

      Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
                {
    #if ANDROID
                    handler.PlatformView.Settings.SetGeolocationEnabled(true);
                    handler.PlatformView.Settings.JavaScriptCanOpenWindowsAutomatically = true;
                    handler.PlatformView.Settings.JavaScriptEnabled = true;
                    handler.PlatformView.SetWebChromeClient(new MyWebChromeClient());
                   
    #endif
                });
    

    In the end. you need to override the OnGeolocationPermissionsShowPrompt method, request location permission by this location simple, you can execute callback.Invoke(origin, true, false); in the end.

    #if ANDROID
        internal class MyWebChromeClient : WebChromeClient
        {     
            public async Task<PermissionStatus> CheckAndRequestLocationPermission()
            {
                PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
               if (status == PermissionStatus.Granted)
                    return status;
               if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
                {
                    // Prompt the user to turn on in settings
                    return status;
                }
               if (Permissions.ShouldShowRationale<Permissions.LocationWhenInUse>())
                {
                    // Prompt the user with additional information as to why the permission is needed
                }
               status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
               return status;
            }
    
    
           public override async void OnGeolocationPermissionsShowPrompt(string? origin, GeolocationPermissions.ICallback? callback)
            {
    
               PermissionStatus permissionStatus = await CheckAndRequestLocationPermission();            
               base.OnGeolocationPermissionsShowPrompt(origin, callback);
               callback.Invoke(origin, true, false);
            }
        }
    
    
    #endif
    

    Best Regards,

    Leon Lu


    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.


0 additional answers

Sort by: Most helpful