This question is almost 7 years old as of time of writing (Apr/20), but still relevant as APIs have changed. I've encountered a similar problem while writing a functional test with Selenium.
As an example, the scenarios that can occur in the canonical Mozilla example :
- The browser does not support geolocation (
!navigator.geolocation)
- With geolocation supported (
getCurrentPosition(success, error))
- access to geolocation denied (
error)
- access to geolocation allowed (
success)
Here is how these scenarios would translate to the Selenium setup:
from selenium import webdriver
# geolocation API not supported
geoDisabled = webdriver.FirefoxOptions()
geoDisabled.set_preference("geo.enabled", False)
browser = webdriver.Firefox(options=geoDisabled)
In order to go down the path of simulating a "Don't Allow" click in the prompt for geo-enabled browsers (by default enabled, check via about:config):
# geolocation supported but denied
geoBlocked = webdriver.FirefoxOptions()
geoBlocked.set_preference("geo.prompt.testing", True)
geoBlocked.set_preference("geo.prompt.testing.allow", False)
browser = webdriver.Firefox(options=geoBlocked)
And finally, simulating the "Allow Location Access" click
# geolocation supported, allowed and location mocked
geoAllowed = webdriver.FirefoxOptions()
geoAllowed.set_preference('geo.prompt.testing', True)
geoAllowed.set_preference('geo.prompt.testing.allow', True)
geoAllowed.set_preference('geo.provider.network.url',
'data:application/json,{"location": {"lat": 51.47, "lng": 0.0}, "accuracy": 100.0}')
browser = webdriver.Firefox(options=geoAllowed)
The geo.wifi.uri attribute does not seem to exist anymore, but has changed to geo.provider.network.url instead. This solution also prevents "random" Firefox profiles being loaded from disk, or JS code executed at runtime to mock the location. It is largely irrelevant whether the brower configuration is set via "Options" (as it is the case with this solution), via "Profiles", or via "DesiredCapabilities". I found Options to be the simplest.