Search code examples
javaseleniumdialoggeolocationdismiss

Dismiss "... wants to know your location" dialog


I am using Selenium + Chromedriver to automate testing of a website. One of the functionalities uses Location Services. I have enabled the Location Service for the Chrome browser that I am using.

But when I run the test, the dialog pictured below shows. enter image description here

The following code finds the alert - but the alert.dismiss() does not seem to work (i.e. the dialog is still present)

try {
            Alert alert = driver.switchTo().alert();
            alert.dismiss();
        } catch (NoAlertPresentException ex) {
            // System.out.println("No alert for this test case.");
        }   

 

How can the test code click the Allow button and have the dialog dismissed? My goal is to click Allow.

--Sam--


Solution

  • Map<String, Object> prefs = new HashMap<String, Object>();
    Map<String, Object> profile = new HashMap<String, Object>();
    prefs.put("googlegeolocationaccess.enabled", true);
    prefs.put("profile.default_content_setting_values.geolocation", 2); // 1:allow 2:block
    prefs.put("profile.default_content_setting_values.notifications", 1);
    prefs.put("profile.managed_default_content_settings", 1);
    options.setExperimentalOption("prefs", prefs);
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    webDriver = new ChromeDriver(capabilities);
    

    you can also try setting prefs.put("googlegeolocationaccess.enabled", false);

    This will make all geo location access request to be blocked or accept by default according to the flag you set before running the driver