Search code examples
c#androidwebviewmaui

How to access location in WebView in .NET MAUI?


My app has permission to access location.

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

I check if the user already gave permission and if not, I'm calling:

await Permissions.RequestAsync<Permissions.LocationWhenInUse>();

But opening a webpage in a WebView control that wants to access the device location does not work, I always get:

User denied the request for Geolocation

What do I need to add / change to be able to read the device location from a WebView control?


Solution

  • Okay got it to work. If someone also has a similar issue, here's the solution:

    Create a custom WebChromeClient and add it to your WebView control by adding the following code to your WebView Loaded-Event:

    #if ANDROID    
        ((IWebViewHandler)myWebView.Handler).PlatformView.SetWebChromeClient(new 
        CustomWebChromeClient());
    #endif
    

    Here's the resource: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/webview?view=net-maui-8.0&pivots=devices-android#handle-permissions-on-android