Mock Firefox Geolocation with selenium webdriver

Geo-location is being considered a hygiene factor these days and is part of most of the websites. Pair it with a responsive web page design and faster wireless internet on devices like iPad, phones, tablets etc – the mix becomes too lucrative for any web designer to miss.

A designer’s adventures with visitor’s data come with a cost though and things become messy for an automation tester when he/she has to test such functionality for a website with a tool like selenium.

Imagine running selenium tests with Firefox browser on a CI pipeline. You were sure your browser detected the correct location when you wrote that automation script, but you cant be certain where the test will launch the browser in an CI/CD environment. Browser, in this case would pick up the current location(you would also need to disable/give consent for the share location dialogs) and run the test which may fail if your assertion is set to verify location you tested while writing the test.

The problem here can be solved by faking your browser’s geolocation altogether while in the test environments for these tests. Firefox provides an easy to automate approach for setting up things.

Note: This is applicable for firefox only and I am exploring ways of doing the same for other browsers using WebDriver.

Firefox’s under-the-hood setting of our interest

You can check your browser’s settings to verify where your geolocation is picked from by entering ‘about:config‘ in the address bar of Firefox. Agree to any warnings related to warranty (take that leap of faith, its worth exploring).

It opens up a plethora of configuration strings, the one you need can be searched – ‘geo.wifi.uri‘. It has the value – ‘https://www.googleapis.com/geolocation/v1/geolocate?key=%GOOGLE_API_KEY%‘ in my case.

Screen Shot 2017-03-22 at 8.13.01 AM

replace it with a string like  –

data:application/json,{“location”: {“lat”: , “lng”: }, “accuracy”: 100.0}

That’s it!! your browser now shows your location as you want it to show.

Doing this in WebDriver

Fortunately, Selenium WebDriver can help up achieve a similar result when launching a browser instance.

var profile = new FirefoxProfile();
profile.setPreference("geo.prompt.testing", true);
profile.setPreference("geo.prompt.testing.allow", true);
profile.setPreference("geo.enabled", true);
profile.setPreference("geo.wifi.uri", 'data:application/json,{"location": {"lat": <lat>, "lng": <long>}, "accuracy": 100.0}');
var browser = new SeleniumBrowser(new FirefoxDriver(profile));

The highlighted lines will add geo location abilities to the browser while the top two will take care of any prompts by consenting to share user’s location.

The browser object returned here can now be used for browsing the webpages and automating with your browser now behaving to be present at the desired location.

Happy Automating !

Advertisements
Mock Firefox Geolocation with selenium webdriver