I have to retrieve a user's location in a WebView
. I do this with the following Javascript:
function getLocation() { navigator.geolocation.getCurrentPosition(displayLocation, handleError); }
But the permission request popup never opens.
I've set these settings:
ws.setJavaScriptEnabled(true); ws.setGeolocationEnabled(true); ws.setJavaScriptCanOpenWindowsAutomatically(true);
What is the correct way to access a user's location from within a WebView
?
Geolocation permissions are applied to an origin, which consists of the host, scheme and port of a URI. In order for web content to use the Geolocation API, permission must be granted for that content's origin. This class stores Geolocation permissions. An origin's permission state can be either allowed or denied.
A callback interface used by the host application to notify the current page that its custom view has been dismissed. class. WebChromeClient.FileChooserParams.
WebView
, using WebSettings.setJavaScriptEnabled(true);
ACCESS_FINE_LOCATION
The WebView
must use a custom WebChromeClient
which implements WebChromeClient.onGeolocationPermissionsShowPrompt()
. This method is called by the WebView
to obtain permission to disclose the user's location to JavaScript. (In the case of the browser, we show a prompt to the user.) The default implementation does nothing, so permission is never obtained and the location is never passed to JavaScript. A simple implementation which always grants permission is ...
webView.setWebChromeClient(new WebChromeClient() { public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } });
Geolocation uses databases to persist cached positions and permissions between sessions. The location of the database is set using WebSettings.setGeolocationDatabasePath(...)
. If the location of the database is not set, the persistent storage will not be available, but Geolocation will continue to function correctly otherwise. To set the location of the databases, use ...
webView.getSettings().setGeolocationDatabasePath( context.getFilesDir().getPath() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With