Problem
We want to manipulate our GeoLocation in the Firefox browser using Selenium WebDriver.
Solution
We have to follow a few steps in order to achieve the desired behavior. We have to create a customized Firefox profile, we have to create a JSON file with the desired location and finally we have to adjust our code to use the customized profile and JSON location file.
- Create a predefined Firefox profile.
- Start the Firefox Profile manager with:
firefox.exe -Pand create a new profile. - Open
about:permissionsin the browser - Locate the entry of the website and change
Share LocationfromAlways AsktoAllow
- Create a JSON file with a GeoLocation.
{
"status": "OK",
"accuracy": 10.0,
"location": {"lat": 52.1771129, "lng": 5.4099848}
}
1 2 3 4 5 |
{
"status": "OK",
"accuracy": 10.0,
"location": {"lat": 52.1771129, "lng": 5.4099848}
}
|
- Use the just created profile and set the
geo.wifi.uripreference before launching the browser. So, the the code will end up like this:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class LocationContextExample {
private static WebDriver driver;
@BeforeClass
public void setUp() {
FirefoxProfile profile = new ProfilesIni().getProfile("dev");
profile.setPreference("geo.wifi.uri", "file://C:/location.json");
driver = new FirefoxDriver(profile);
driver.get("http://www.w3schools.com/html5/html5_geolocation.asp");
}
@AfterClass
public void tearDown() {
driver.close();
driver.quit();
}
@Test
public void getLocation() throws InterruptedException {
driver.findElement(By.cssSelector("p#demo button")).click();
Thread.sleep(5000);
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class LocationContextExample {
private static WebDriver driver;
@BeforeClass
public void setUp() {
FirefoxProfile profile = new ProfilesIni().getProfile("dev");
profile.setPreference("geo.wifi.uri", "file://C:/location.json");
driver = new FirefoxDriver(profile);
driver.get("http://www.w3schools.com/html5/html5_geolocation.asp");
}
@AfterClass
public void tearDown() {
driver.close();
driver.quit();
}
@Test
public void getLocation() throws InterruptedException {
driver.findElement(By.cssSelector("p#demo button")).click();
Thread.sleep(5000);
}
}
|
