Testing Geolocation, Timezone and Locale
Test location, timezone and language features in Selenium: geolocation overrides, permissions, Accept-Language prefs, and timezone via CDP, BiDi and TZ.
“Show stores near me”, “your delivery arrives Tuesday 14:00”, “Preis: 1.299,00 €”. Features that depend on where the user is, what time it is for them and what language they speak are full of bugs that never appear on the developer’s machine in one city, one timezone and one locale. A booking that lands on the wrong day for users east of UTC, a German number format that breaks the price parser, a geolocation prompt that blocks the page when denied: these ship because nobody tested them.
Selenium can control all three dimensions, but each is controlled at a different layer, and the right mechanism differs by browser. This lesson maps them out.
| What you want to vary | Where it lives | Chromium | Firefox |
|---|---|---|---|
Geolocation (navigator.geolocation) | Browser emulation + permission | CDP or BiDi override, permission grant | BiDi override, or prefs |
| Geolocation permission (allow / deny / prompt) | Browser permission store | Prefs, CDP Browser.grantPermissions | Prefs |
Timezone (Date, Intl) | Browser process environment or emulation | CDP Emulation.setTimezoneOverride, TZ env (Linux/macOS) | TZ env (Linux/macOS), BiDi where supported |
Formatting locale (Intl defaults) | Browser emulation or UI language | CDP Emulation.setLocaleOverride, --lang | intl.locale.requested pref |
Accept-Language header, navigator.languages | Browser preferences | intl.accept_languages pref | intl.accept_languages pref |
| Server-side location (IP-based) | Network origin | Proxy, cloud grid region, or test header | Same |
Geolocation
The Geolocation API needs two things to return coordinates: a position source and permission. In a fresh WebDriver profile, permission is not granted, so getCurrentPosition either shows a prompt (headed) or fails. Handle both explicitly.
Chromium: CDP override plus permission grant
executeCdpCommand sends a raw DevTools command by name. It is the least fragile way to use CDP because it needs no version-specific imports; see Chrome DevTools Protocol for the trade-offs.
ChromiumDriver chromium = (ChromiumDriver) driver;
// Grant permission for the origin under testchromium.executeCdpCommand("Browser.grantPermissions", Map.of( "origin", "https://app.example.com", "permissions", List.of("geolocation")));
// Pretend to be in Tokyochromium.executeCdpCommand("Emulation.setGeolocationOverride", Map.of( "latitude", 35.6762, "longitude", 139.6503, "accuracy", 50));
driver.get("https://app.example.com/stores/nearby");WebElement first = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".store-result")));assertTrue(first.getText().contains("Tokyo"));driver.execute_cdp_cmd("Browser.grantPermissions", { "origin": "https://app.example.com", "permissions": ["geolocation"],})
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", { "latitude": 35.6762, "longitude": 139.6503, "accuracy": 50,})
driver.get("https://app.example.com/stores/nearby")first = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, ".store-result")))assert "Tokyo" in first.textawait driver.sendDevToolsCommand('Browser.grantPermissions', {origin: 'https://app.example.com',permissions: ['geolocation'],});
await driver.sendDevToolsCommand('Emulation.setGeolocationOverride', {latitude: 35.6762, longitude: 139.6503, accuracy: 50,});
await driver.get('https://app.example.com/stores/nearby');const first = await driver.wait(until.elementLocated(By.css('.store-result')), 10000);assert.ok((await first.getText()).includes('Tokyo'));var chromium = (ChromiumDriver)driver;
chromium.ExecuteCdpCommand("Browser.grantPermissions", new Dictionary<string, object>{ ["origin"] = "https://app.example.com", ["permissions"] = new[] { "geolocation" },});
chromium.ExecuteCdpCommand("Emulation.setGeolocationOverride", new Dictionary<string, object>{ ["latitude"] = 35.6762, ["longitude"] = 139.6503, ["accuracy"] = 50,});
driver.Navigate().GoToUrl("https://app.example.com/stores/nearby");var first = new WebDriverWait(driver, TimeSpan.FromSeconds(10)) .Until(d => d.FindElement(By.CssSelector(".store-result")));Assert.That(first.Text, Does.Contain("Tokyo"));Emulation overrides apply to the current tab. A new tab or window starts without them, so re-apply after switching. To simulate “position unavailable”, call Emulation.setGeolocationOverride with no coordinates; to clear the override, call Emulation.clearGeolocationOverride.
Cross-browser: BiDi geolocation override
The BiDi emulation.setGeolocationOverride command works in Chrome, Edge and Firefox, which makes it the better long-term choice. Its Selenium APIs are still settling, as noted in WebDriver BiDi.
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(35.6762, 139.6503)).contexts(List.of(driver.getWindowHandle())));
driver.get("https://app.example.com/stores/nearby");driver.emulation.set_geolocation_override( coordinates={"latitude": 35.6762, "longitude": 139.6503}, contexts=[driver.current_window_handle],)
driver.get("https://app.example.com/stores/nearby")const bidi = await driver.getBidi();
await bidi.send({method: 'emulation.setGeolocationOverride',params: { coordinates: { latitude: 35.6762, longitude: 139.6503 }, 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(35.6762, 139.6503), new() { Contexts = [context] });
await context.NavigateAsync("https://app.example.com/stores/nearby");The BiDi override supplies coordinates; permission is a separate concern. Grant it with prefs (below) or CDP on Chromium. The W3C also defines a permissions.setPermission BiDi extension command; check your binding’s release notes for a high-level API before relying on it.
Permission prompts: allow, deny, and the prompt itself
Test all three permission states, because each produces different UI: coordinates (allowed), a fallback such as “enter your postcode” (denied), or a prompt the user may ignore (default). Prefs set at startup are the simplest, most portable approach.
// Chrome / Edge: 1 = allow, 2 = blockChromeOptions chrome = new ChromeOptions();chrome.setExperimentalOption("prefs", Map.of( "profile.default_content_setting_values.geolocation", 2)); // test the denied path
// Firefox: allow with a fixed position from a data: URL network providerFirefoxOptions firefox = new FirefoxOptions();firefox.addPreference("geo.prompt.testing", true);firefox.addPreference("geo.prompt.testing.allow", true);firefox.addPreference("geo.provider.network.url", "data:application/json,{\"location\":{\"lat\":35.6762,\"lng\":139.6503},\"accuracy\":50}");// Make Firefox use the network provider instead of the OS location servicefirefox.addPreference("geo.provider.use_corelocation", false); // macOSfirefox.addPreference("geo.provider.ms-windows-location", false); // Windowsfirefox.addPreference("geo.provider.use_geoclue", false); // Linux# Chrome / Edge: 1 = allow, 2 = blockchrome = webdriver.ChromeOptions()chrome.add_experimental_option("prefs", { "profile.default_content_setting_values.geolocation": 2, # test the denied path})
# Firefox: allow with a fixed positionfirefox = webdriver.FirefoxOptions()firefox.set_preference("geo.prompt.testing", True)firefox.set_preference("geo.prompt.testing.allow", True)firefox.set_preference( "geo.provider.network.url", 'data:application/json,{"location":{"lat":35.6762,"lng":139.6503},"accuracy":50}')firefox.set_preference("geo.provider.use_corelocation", False)firefox.set_preference("geo.provider.ms-windows-location", False)firefox.set_preference("geo.provider.use_geoclue", False)const chrome = require('selenium-webdriver/chrome');const firefox = require('selenium-webdriver/firefox');
// Chrome / Edge: 1 = allow, 2 = blockconst chromeOptions = new chrome.Options().setUserPreferences({'profile.default_content_setting_values.geolocation': 2,});
// Firefox: allow with a fixed positionconst firefoxOptions = new firefox.Options().setPreference('geo.prompt.testing', true).setPreference('geo.prompt.testing.allow', true).setPreference('geo.provider.network.url', 'data:application/json,{"location":{"lat":35.6762,"lng":139.6503},"accuracy":50}').setPreference('geo.provider.use_corelocation', false).setPreference('geo.provider.ms-windows-location', false).setPreference('geo.provider.use_geoclue', false);// Chrome / Edge: 1 = allow, 2 = blockvar chrome = new ChromeOptions();chrome.AddUserProfilePreference("profile.default_content_setting_values.geolocation", 2);
// Firefox: allow with a fixed positionvar firefox = new FirefoxOptions();firefox.SetPreference("geo.prompt.testing", true);firefox.SetPreference("geo.prompt.testing.allow", true);firefox.SetPreference("geo.provider.network.url", "data:application/json,{\"location\":{\"lat\":35.6762,\"lng\":139.6503},\"accuracy\":50}");firefox.SetPreference("geo.provider.use_corelocation", false);firefox.SetPreference("geo.provider.ms-windows-location", false);firefox.SetPreference("geo.provider.use_geoclue", false);Permission prompts are browser UI, not page content, so they are not JavaScript alerts and switchTo().alert() will not dismiss them (that throws NoAlertPresentException; compare Unexpected Alert Open for real alerts). Decide the permission state before the page asks. Firefox pref names have changed occasionally over the years; if a pref seems to have no effect, check about:config in the Firefox version you run.
Assert the denied path deliberately. A store locator that spins forever when permission is denied is a real and common bug:
deny geolocation -> open /stores/nearby -> assert "Enter a postcode" field is visible within 5 sServer-side location is a different problem
Many sites decide location on the server from the client IP (currency, region redirects, content licensing). Browser geolocation overrides do nothing for that. Options:
- A test-only header or cookie your edge honours in non-production environments (for example,
X-Test-Country: JP), injected with BiDi network interception (see Network Interception with BiDi) or set as a cookie. - A proxy or VPN exit in the target country, configured through the browser’s proxy settings.
- Cloud grid regions. Several cloud providers offer IP geolocation per session; see Cloud Testing Platforms.
Timezone
Timezone bugs are the most expensive of the three: wrong-day bookings, deadlines that expire early, reports that drop a day of data. Two complementary techniques control the browser’s timezone.
CDP timezone override (Chromium, any OS)
Emulation.setTimezoneOverride changes what Date and Intl.DateTimeFormat().resolvedOptions().timeZone report for the tab, on every operating system, without restarting the browser.
ChromiumDriver chromium = (ChromiumDriver) driver;
for (String tz : List.of("Pacific/Auckland", "Asia/Kolkata", "Europe/London", "America/Los_Angeles")) { chromium.executeCdpCommand("Emulation.setTimezoneOverride", Map.of("timezoneId", tz)); driver.get("https://app.example.com/bookings/42");
String reported = (String) chromium.executeScript( "return Intl.DateTimeFormat().resolvedOptions().timeZone;"); assertEquals(tz, reported);
// The booking is at 09:00 local time at the venue, regardless of the viewer's timezone assertEquals("Tue 14 Jul, 09:00", driver.findElement(By.cssSelector("[data-testid='start-time']")).getText(), "Wrong start time shown in " + tz);}for tz in ["Pacific/Auckland", "Asia/Kolkata", "Europe/London", "America/Los_Angeles"]: driver.execute_cdp_cmd("Emulation.setTimezoneOverride", {"timezoneId": tz}) driver.get("https://app.example.com/bookings/42")
assert driver.execute_script("return Intl.DateTimeFormat().resolvedOptions().timeZone;") == tz
shown = driver.find_element(By.CSS_SELECTOR, "[data-testid='start-time']").text assert shown == "Tue 14 Jul, 09:00", f"Wrong start time shown in {tz}: {shown}"for (const tz of ['Pacific/Auckland', 'Asia/Kolkata', 'Europe/London', 'America/Los_Angeles']) {await driver.sendDevToolsCommand('Emulation.setTimezoneOverride', { timezoneId: tz });await driver.get('https://app.example.com/bookings/42');
assert.strictEqual( await driver.executeScript('return Intl.DateTimeFormat().resolvedOptions().timeZone;'), tz);
const shown = await driver.findElement(By.css("[data-testid='start-time']")).getText();assert.strictEqual(shown, 'Tue 14 Jul, 09:00', `Wrong start time shown in ${tz}`);}var chromium = (ChromiumDriver)driver;
foreach (var tz in new[] { "Pacific/Auckland", "Asia/Kolkata", "Europe/London", "America/Los_Angeles" }){ chromium.ExecuteCdpCommand("Emulation.setTimezoneOverride", new Dictionary<string, object> { ["timezoneId"] = tz }); driver.Navigate().GoToUrl("https://app.example.com/bookings/42");
var reported = (string)chromium.ExecuteScript("return Intl.DateTimeFormat().resolvedOptions().timeZone;"); Assert.That(reported, Is.EqualTo(tz));
var shown = driver.FindElement(By.CssSelector("[data-testid='start-time']")).Text; Assert.That(shown, Is.EqualTo("Tue 14 Jul, 09:00"), $"Wrong start time shown in {tz}");}Always assert the reported timezone as in the example. If the override silently did not apply (wrong tab, unsupported browser), the test would otherwise pass in your machine’s timezone and prove nothing.
Which timezones to test. One far east of UTC (Pacific/Auckland, UTC+12/13), one far west (America/Los_Angeles or Pacific/Honolulu), one with a half-hour offset (Asia/Kolkata), and one with daylight saving transitions near your test dates (Europe/London, America/New_York). Test dates near midnight UTC and near DST changes; that is where off-by-one-day bugs live.
TZ environment variable (Linux and macOS)
On Linux and macOS, browsers read the TZ environment variable at startup. Because the driver launches the browser, set TZ in the driver service’s environment and the browser inherits it. This works for Firefox as well as Chrome and affects the whole browser, including every tab and worker.
ChromeDriverService service = new ChromeDriverService.Builder() .withEnvironment(Map.of("TZ", "Asia/Kolkata")) .build();WebDriver driver = new ChromeDriver(service, new ChromeOptions());
// Firefox: GeckoDriverService.Builder().withEnvironment(...) works the same wayimport osfrom selenium.webdriver.chrome.service import Service
# env replaces the driver's environment, so start from the current oneservice = Service(env={**os.environ, "TZ": "Asia/Kolkata"})driver = webdriver.Chrome(service=service)
# Firefox: selenium.webdriver.firefox.service.Service(env=...) works the same wayconst chrome = require('selenium-webdriver/chrome');
const service = new chrome.ServiceBuilder().setEnvironment({ ...process.env, TZ: 'Asia/Kolkata' });
const driver = await new Builder().forBrowser('chrome').setChromeService(service).build();For .NET, the simplest portable route is the CDP override above for Chromium; alternatively set TZ in the test process environment before the driver starts so that the driver and browser inherit it.
Limitations: Windows browsers ignore TZ, and on a remote Grid the variable must be set on the node, not your machine. Selenium’s Docker images accept a TZ environment variable on the container for exactly this purpose (docker run -e TZ=Asia/Kolkata selenium/standalone-chrome), which is often the cleanest option in CI; see Docker and Testcontainers.
BiDi timezone and locale emulation
The WebDriver BiDi specification has added emulation.setTimezoneOverride and emulation.setLocaleOverride, with implementations landing in Chrome and Firefox. These will become the cross-browser answer. High-level Selenium APIs for them are not consistent across bindings yet; JavaScript can send the raw command today with the same bidi.send pattern used for geolocation above (method: 'emulation.setTimezoneOverride', params: { timezone: 'Asia/Kolkata', contexts: [...] }). Check the Releases page before adopting them in other bindings.
Language and Locale
“Locale” covers three separate things that are easy to conflate:
| Signal | Who reads it | How to set it |
|---|---|---|
Accept-Language request header | The server (picks translation, redirects to /de/) | intl.accept_languages pref (Chrome, Firefox) |
navigator.language / navigator.languages | Client-side i18n libraries | intl.accept_languages pref; Chrome --lang |
Default Intl formatting locale (numbers, dates) | toLocaleString(), Intl.NumberFormat() without arguments | Chrome --lang, CDP Emulation.setLocaleOverride; Firefox intl.locale.requested |
Most apps choose their language from Accept-Language or navigator.languages, so the pref is the one to set first.
// Chrome / EdgeChromeOptions chrome = new ChromeOptions();chrome.addArguments("--lang=de-DE");chrome.setExperimentalOption("prefs", Map.of("intl.accept_languages", "de-DE,de"));
// FirefoxFirefoxOptions firefox = new FirefoxOptions();firefox.addPreference("intl.accept_languages", "de-DE, de");firefox.addPreference("intl.locale.requested", "de-DE");
WebDriver driver = new ChromeDriver(chrome);driver.get("https://app.example.com/pricing");assertEquals("de-DE", ((JavascriptExecutor) driver).executeScript("return navigator.language;"));assertTrue(driver.findElement(By.cssSelector(".price")).getText().matches(".*\\d+,\\d{2}\\s?€.*"));import re
# Chrome / Edgechrome = webdriver.ChromeOptions()chrome.add_argument("--lang=de-DE")chrome.add_experimental_option("prefs", {"intl.accept_languages": "de-DE,de"})
# Firefoxfirefox = webdriver.FirefoxOptions()firefox.set_preference("intl.accept_languages", "de-DE, de")firefox.set_preference("intl.locale.requested", "de-DE")
driver = webdriver.Chrome(options=chrome)driver.get("https://app.example.com/pricing")assert driver.execute_script("return navigator.language;") == "de-DE"assert re.search(r"\d+,\d{2}\s?€", driver.find_element(By.CSS_SELECTOR, ".price").text)// Chrome / Edgeconst chromeOptions = new chrome.Options().addArguments('--lang=de-DE').setUserPreferences({ 'intl.accept_languages': 'de-DE,de' });
// Firefoxconst firefoxOptions = new firefox.Options().setPreference('intl.accept_languages', 'de-DE, de').setPreference('intl.locale.requested', 'de-DE');
const driver = await new Builder().forBrowser('chrome').setChromeOptions(chromeOptions).build();await driver.get('https://app.example.com/pricing');assert.strictEqual(await driver.executeScript('return navigator.language;'), 'de-DE');assert.match(await driver.findElement(By.css('.price')).getText(), /\d+,\d{2}\s?€/);// Chrome / Edgevar chrome = new ChromeOptions();chrome.AddArgument("--lang=de-DE");chrome.AddUserProfilePreference("intl.accept_languages", "de-DE,de");
// Firefoxvar firefox = new FirefoxOptions();firefox.SetPreference("intl.accept_languages", "de-DE, de");firefox.SetPreference("intl.locale.requested", "de-DE");
var driver = new ChromeDriver(chrome);driver.Navigate().GoToUrl("https://app.example.com/pricing");Assert.That(((IJavaScriptExecutor)driver).ExecuteScript("return navigator.language;"), Is.EqualTo("de-DE"));Assert.That(driver.FindElement(By.CssSelector(".price")).Text, Does.Match(@"\d+,\d{2}\s?€"));Platform notes:
- Chrome
--langon Linux is not reliably honoured; Chrome on Linux takes its UI language from theLANGUAGE/LANGenvironment variables. Set those in the driver service environment (as withTZ) or rely on theintl.accept_languagespref, which works everywhere. - Language prefs apply at startup. You cannot switch language mid-session with prefs. To test several languages, create a session per language (parameterise the driver factory), or use the CDP
Emulation.setLocaleOverridecommand forIntlformatting and a BiDi request interceptor to rewriteAccept-Languagefor the server. - Use the app’s own switch where one exists. If the app has a language picker or a
?lang=deparameter, one UI test should exercise it; the remaining localisation tests can use prefs for speed.
Testing localised content sensibly
- Do not hard-code translated strings in tests for every language. Assert on structure and formats (a price matches the locale’s pattern, a date has the day before the month), and keep exact-string assertions for a single reference language.
- Pseudo-localisation (an
en-XAstyle locale that wraps strings in brackets and accents, and lengthens them by 30 to 40 percent) catches untranslated strings and truncation bugs in one pass, without anyone reading German. Combine it with visual regression testing to catch overflow. - Right-to-left languages (Arabic, Hebrew) are a layout test as much as a translation test: icons that should mirror, padding on the wrong side, mixed-direction text in inputs.
- Parse numbers and dates in the locale, not with English assumptions. “1.299,00” is one thousand two hundred ninety-nine in German, and a test helper that strips commas will read it as 1.29900.
Putting It Together: A Location Context Fixture
Wrap these mechanisms in one place so tests declare intent (“as a user in Tokyo, in Japanese, at 23:30 local time”) rather than juggling prefs and CDP calls.
LocationContext( geolocation = (35.6762, 139.6503) | DENIED | PROMPT, timezone = "Asia/Tokyo", locale = "ja-JP") -> at driver creation: language prefs/args, geolocation permission prefs, TZ in service env -> after creation (Chromium): CDP timezone + geolocation overrides, verify via executeScript -> after creation (Firefox): BiDi geolocation override, verify timezone/locale via executeScriptStartup-time settings (language, permission prefs, TZ) belong in the driver factory; per-tab overrides (CDP and BiDi) belong in a helper called after navigation to a new tab. The verification step (Intl.DateTimeFormat().resolvedOptions(), navigator.languages) protects you from silently ineffective configuration, which is the main failure mode of this whole area.
For freezing the current time itself (to test “expires in 2 days” logic deterministically), the browser offers no WebDriver-level clock control. The usual approaches are a test-only server time override, or installing a fake clock in the page with a BiDi preload script before the app’s scripts run; see the preload scripts section of WebDriver BiDi.
Summary
- Geolocation needs both coordinates and permission: CDP or BiDi for coordinates, prefs or CDP
Browser.grantPermissionsfor permission; test allowed, denied and unavailable paths. - Server-side, IP-based location needs a proxy, a cloud region or a test header, not a browser override.
- Timezone: CDP
Emulation.setTimezoneOverrideon Chromium (any OS),TZin the driver service or container environment on Linux and macOS, BiDi overrides as they mature. Always verify the effective timezone in the page. - Language:
intl.accept_languageseverywhere, plus--lang(Chrome) orintl.locale.requested(Firefox) for formatting defaults; one session per language. - Centralise it in a location-context fixture that applies settings at the right layer and verifies them.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.