Fake the Browser's Geolocation
Make navigator.geolocation report chosen coordinates: grant the permission up front, then override the location with WebDriver BiDi or Chrome DevTools.
Problem
A store locator calls navigator.geolocation.getCurrentPosition(). In CI the browser has no location (or the CI provider’s data centre location), and a permission prompt blocks the page the first time. You need the app to believe the user is in London for one test and Tokyo for the next.
Solution
Two steps: pre-grant the geolocation permission so no prompt appears, then override the coordinates before the page asks for them. On Chrome and Edge the simplest override is the DevTools command; the WebDriver BiDi emulation.setGeolocationOverride command is the cross-browser, standards-based option.
Step 1: Grant the permission
// Chrome / Edge: allow geolocation for all sitesChromeOptions options = new ChromeOptions();options.setExperimentalOption("prefs", Map.of("profile.default_content_setting_values.geolocation", 1));options.setCapability("webSocketUrl", true); // needed for the BiDi override
// Firefox: auto-allow geolocation promptsFirefoxOptions ff = new FirefoxOptions();ff.addPreference("geo.prompt.testing", true);ff.addPreference("geo.prompt.testing.allow", true);The same preferences work from every binding (add_experimental_option("prefs", ...), set_preference(...), setUserPreferences(...), AddUserProfilePreference(...)).
Step 2: Override the coordinates
import org.openqa.selenium.bidi.module.Emulation;import org.openqa.selenium.bidi.emulation.GeolocationCoordinates;import org.openqa.selenium.bidi.emulation.SetGeolocationOverrideParameters;
Emulation emulation = new Emulation(driver);emulation.setGeolocationOverride(new SetGeolocationOverrideParameters( new GeolocationCoordinates(51.5074, -0.1278)) .contexts(List.of(driver.getWindowHandle())));
driver.get("https://app.example.com/stores/nearby");WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));wait.until(ExpectedConditions.textToBePresentInElementLocated(By.cssSelector(".nearest-store"), "London"));driver.emulation.set_geolocation_override( coordinates={"latitude": 51.5074, "longitude": -0.1278}, contexts=[driver.current_window_handle],)
driver.get("https://app.example.com/stores/nearby")WebDriverWait(driver, 10).until( EC.text_to_be_present_in_element((By.CSS_SELECTOR, ".nearest-store"), "London"))// Low-level: send the spec command over the BiDi connectionconst bidi = await driver.getBidi();await bidi.send({method: 'emulation.setGeolocationOverride',params: { coordinates: { latitude: 51.5074, longitude: -0.1278 }, contexts: [await driver.getWindowHandle()],},});
await driver.get('https://app.example.com/stores/nearby');var bidi = await driver.AsBiDiAsync();var context = await driver.AsBiDiContextAsync();
await bidi.Emulation.SetGeolocationOverrideAsync( new GeolocationCoordinates(51.5074, -0.1278), new() { Contexts = [context] });
await context.NavigateAsync("https://app.example.com/stores/nearby");ChromiumDriver chrome = (ChromiumDriver) driver;chrome.executeCdpCommand("Emulation.setGeolocationOverride", Map.of("latitude", 35.6762, "longitude", 139.6503, "accuracy", 10));driver.get("https://app.example.com/stores/nearby");driver.execute_cdp_cmd("Emulation.setGeolocationOverride", {"latitude": 35.6762, "longitude": 139.6503, "accuracy": 10})driver.get("https://app.example.com/stores/nearby")await driver.sendDevToolsCommand('Emulation.setGeolocationOverride', {latitude: 35.6762, longitude: 139.6503, accuracy: 10,});await driver.get('https://app.example.com/stores/nearby');var chrome = (ChromiumDriver)driver;chrome.ExecuteCdpCommand("Emulation.setGeolocationOverride", new(){ ["latitude"] = 35.6762, ["longitude"] = 139.6503, ["accuracy"] = 10,});driver.Navigate().GoToUrl("https://app.example.com/stores/nearby");Why It Works
The override replaces the browser’s position source, so getCurrentPosition() and watchPosition() resolve with your coordinates immediately, with no network location lookup. Granting the permission first matters: without it, the page shows a native prompt that WebDriver cannot click, and the app’s error callback fires instead. Setting the override before get() ensures the very first geolocation call on page load sees it.
Gotchas
- BiDi emulation is still settling. Method and class names have changed between minor Selenium versions. Pin your Selenium version for tests that depend on it and check the Releases page before upgrading.
- Override per browsing context. The BiDi override applies to the contexts you pass. A link that opens a new tab gets a new context without the override; set it again after switching.
- CDP is Chromium-only and needs a local
ChromiumDriver(or an augmented remote one). Firefox removed CDP support in Selenium 4.29; use BiDi there. - Timezone and locale are separate. Pretending to be in Tokyo does not change
Intltimezone or language. Set those separately if the app uses them. - Testing denial. To test the “location blocked” path, set the preference to
2(block) in Chrome, or leavegeo.prompt.testing.allowfalse in Firefox.
Learn the theory
- WebDriver BiDi Enable the bidirectional protocol and use it for console log capture, JavaScript error detection, basic authentication, DOM mutation events, preload scripts, emulation and web extensions, with browser support and migration guidance as of Selenium 4.52.
- Chrome DevTools Protocol (CDP) What CDP gives Selenium on Chromium browsers, how to use it for network throttling, device emulation and performance metrics, why it is version-locked, and when to choose BiDi instead.