5
votes

I am creating some end-to-end tests for a web app using Selenium.

I am working in Python and using the Firefox driver

driver = webdriver.Firefox()

The problem is that my web app using HTML5 geolocation, and it seems that everytime I run my tests, I have to click the 'Allow Location' popup in Firefox, making my tests less than automated.

Is there a way to force the Selenium Firefox driver to always allow geolocation without prompting?

9
Not sure about the -proper- solution, however if you know WHEN the pop-up will come up (i.e. it doesn't come up unexpectedly) then you can probably work around this issue using win32ole send_keys..and hit on enter when it pops-up ;) - Xwris Stoixeia

9 Answers

0
votes

I believe the default is to launch Firefox with a new, anonymous profile. You can launch selenium with -Dwebdriver.firefox.profile=whatever, where "whatever" is the name of a profile when you launch firefox -P.

To make sure there's no weirdness with persistent logins and other cookies:

  • Launch Firefox with "firefox -P"
  • Pick the profile you'll launch the tests with
  • Edit -> Preferences -> Privacy, select Use custom settings for history
  • Tell Firefox to keep cookies until "I close Firefox"
7
votes

You can force browser to return some predefined location without permission requests.

Just execute the following JavaScript code:

"navigator.geolocation.getCurrentPosition = function(success) { success({coords: {latitude: 50.455755, longitude: 30.511565}}); }"

Tested in Firefox and Chrome.

3
votes

Because I reached the same problem almost 3 years after this question was asked, and None of above answers were satisfying for me. I like to show solution I use.

So the answer I found on this blog.

And use it on my python code this way:

@classmethod
def setUpClass(cls):
    cls.binary = FirefoxBinary(FF_BINARY_PATH)
    cls.profile = FirefoxProfile()
    cls.profile.set_preference("geo.prompt.testing", True)
    cls.profile.set_preference("geo.prompt.testing.allow", True)
    cls.profile.set_preference('geo.wifi.uri', GEOLOCATION_PATH)
    cls.driver = Firefox(firefox_binary=cls.binary, firefox_profile=cls.profile)

On GEOLOCATION_PATH is my path to JSON file:

{
    "status": "OK",
    "accuracy": 10.0,
    "location": {
        "lat": 50.850780,
        "lng": 4.358138,
        "latitude": 50.850780,
        "longitude": 4.358138,
        "accuracy": 10.0
    }
}
3
votes

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.

1
votes

Just stumbled upon this problem today and I knew there should exist a simple and quick way of dealing with this. Here's how I solved it:

  1. Create a new Firefox profile that will be used by Selenium. You can do it by typing about:profiles and then clicking on 'Create new profile'. A step by step instruction can be found in Mozilla's docs.
  2. Head to the site that needs the permissions and wait for it to ask you to grant them. Grant them and check the "Remember this decision" box.
  3. You'll need to know where your profile is stored, so that Selenium can use it. You can find the location in about:profiles. Here I created an "example_profile" and then copied the "Root directory" path: about:profiles

  4. You can then pass the path as a parameter while instantiating a Firefox browser like this:

    root_directory_path = "/.../Firefox/Profiles/loeiok2p.example_profile"
    driver = webdriver.Firefox(firefox_profile=root_directory_path)
    

Selenium should use the profile with granted permissions and the popup should not reappear.

0
votes

Here is more refined answer from one of the answers above. This adds some timeout before doing geolocation success callback, as usually JavaScript is written in such a manner that geolocation coordinates are not expected to be available until there has been one cycle back to the event loop.

This allows also tracing the spoofing through Web Console.

SPOOF_LOCATION_JS = """
(function() {
console.log('Preparing geo spoofing');
navigator.geolocation.getCurrentPosition = function(success) {
    console.log("getCurrentPosition() called");
    setTimeout(function() { console.log("Sending out fake coordinates"); success({coords: {latitude: 50.455755, longitude: 30.511565}}); }, 500);
};
console.log("Finished geospoofing")})();
"""


browser.evaluate_script(SPOOF_LOCATION_JS.replace("\n", " "))
0
votes

None of the above worked for me but this did:

got answer from: https://security.stackexchange.com/questions/147166/how-can-you-fake-geolocation-in-firefox

from selenium import webdriver

profile = webdriver.FirefoxProfile()

profile.set_preference("geo.prompt.testing", True)
profile.set_preference("geo.prompt.testing.allow", True)
profile.set_preference('geo.wifi.uri',
                       'data:application/json,{"location": {"lat": 40.7590, "lng": -73.9845}, "accuracy": 27000.0}')


driver = webdriver.Firefox(firefox_profile=profile)

driver.get('https://www.where-am-i.net/')
0
votes

I am using Firefox 74.0 with Selenium/Python 3.141.0 and the following places me in NYC

profile = FirefoxProfile()
profile.set_preference("geo.prompt.testing", True)
profile.set_preference("geo.prompt.testing.allow", True)
profile.set_preference("geo.provider.testing", True)
"geo.provider.network.url", "data:application/json,{"location": {"lat": 40.7590, "lng": -73.9845}, "accuracy": 27000.0}")
-2
votes

Would it be enough to just allow it one time manually and then allow python do to the job?

Because you can easily allow by setting this in the website properties in Firefox: enter image description here