-2

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--

S P
  • 101
  • 2
  • 13

1 Answers1

1
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

PDHide
  • 18,113
  • 2
  • 31
  • 46
  • Thanks for the reply.The same dialog pops up even after I added prefs.put("googlegeolocationaccess.enabled", false); – S P Jan 11 '21 at 16:56
  • 1
    @sp you have to set it to true and set prefs.put("profile.default_content_setting_values.geolocation as 2 , use the code as it is – PDHide Jan 11 '21 at 17:07
  • Thank you, @PDHide. Now the code works like charm - the dialog in the image above is not shown in either case. – S P Jan 12 '21 at 17:01
  • Just discovered that if the browser is instantiated in Incognito mode, the dialog to allow/disallow "Know your location" shows. Is the code supposed to work only in non-Incognito mode? – S P Jan 12 '21 at 17:31
  • I think in incognito location service is disabled so the code won't work I am not sure why – PDHide Jan 12 '21 at 18:17
  • Thanks. I guess, I won't run the tests in incognoto mode then :) – S P Jan 12 '21 at 18:37
  • please accept the answer by clicking the tick sign – PDHide Mar 15 '21 at 17:36