How do I enable geolocation support in chromedriver?
Asked Answered
G

9

15

I need to test a JS geolocation functionality with Selenium and I am using chromedriver to run the test on the latest Chrome.

The problem is now that Chrome prompts me to enable Geolocation during the test and that I don't know how to click that little bar on runtime, so I am desperately looking for a way to start the chromedriver and chrome with some option or trigger to enable this by default. All I could find here was however how I can disable geolocation altogether.

How can I solve this issue?

Gamez answered 7/12, 2011 at 7:31 Comment(0)
H
18

In the known issues section of the chromedriver wiki they said that you Cannot specify a custom profile

This is why it seems to me that @Sotomajor answer about using profile with Chrome as you would do with firefox will not work.

In one of my integration tests I faced the same issue. But because I was not bothering about the real geolocation values, all I had to do is to mock window.navigator.gelocation

In you java test code put this workaround to avoid Chrome geoloc permission info bar.

chromeDriver.executeScript("window.navigator.geolocation.getCurrentPosition = function(success) {
  var position = {
    "coords": {
      "latitude": "555",
      "longitude": "999"
    }
  };
  success(position);
}");

latitude (555) and longitude (999) values here are just test value

Hush answered 3/4, 2012 at 15:36 Comment(2)
The returned values should be scalar numbers not strings.Pigpen
Just to point out that this same JS will work on Safari/ChromeAdenovirus
G
3

Approach which worked for me in Firefox was to visit that site manually first, give those permissions and afterwards copy firefox profile somewhere outside and create selenium firefox instance with that profile.

So:

  1. cp -r ~/Library/Application\ Support/Firefox/Profiles/tp3khne7.default /tmp/ff.profile

  2. Creating FF instance:

    FirefoxProfile firefoxProfile = new FirefoxProfile(new File("/tmp/ff.profile"));
    FirefoxDriver driver = new FirefoxDriver(firefoxProfile);
    

I'm pretty sure that something similar should be applicable to Chrome. Although api of profile loading is a bit different. You can check it here: http://code.google.com/p/selenium/wiki/ChromeDriver

Gobioid answered 22/12, 2011 at 10:28 Comment(1)
Thanks for the useful hint, not quite what I was looking for (since the host part of the URL I load into might change over time I'd have to update the profile each time or provide different profiles), but better than nothing as of now.Gamez
I
3

Here is how I did it with capybara for cucumber tests

Capybara.register_driver :selenium2 do |app|      
  profile = Selenium::WebDriver::Chrome::Profile.new
  profile['geolocation.default_content_setting'] = 1

  config = { :browser => :chrome, :profile => profile }    
  Capybara::Selenium::Driver.new(app, config)
end

And there is link to other usefull profile settings: pref_names.cc

Take a look at "Tweaking profile preferences" in RubyBindings

Innerdirected answered 5/1, 2012 at 15:51 Comment(0)
M
2

As for your initial question:

You should start Firefox manually once - and select the profile you use for Selenium.

Type about:permissions in the address line; find the name of your host - and select share location : "allow".

That's all. Now your Selenium test cases will not see that dreaded browser dialog which is not in the DOM.

Merrymerryandrew answered 9/4, 2013 at 8:53 Comment(0)
S
2

I took your method but it can not working. I did not find "BaseUrls.Root.AbsoluteUri" in Chrome's Preferences config. And use a script for test

chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("proxy-server=http://127.0.0.1:1087")
    prefs = {
        'profile.default_content_setting_values':
            {
                'notifications': 1,
                'geolocation': 1
            },
        'devtools.preferences': {
            'emulation.geolocationOverride': "\"[email protected]:\"",
        },
        'profile.content_settings.exceptions.geolocation':{
            'BaseUrls.Root.AbsoluteUri': {
                'last_modified': '13160237885099795',
                'setting': '1'
            }
        },
        'profile.geolocation.default_content_setting': 1

    }

    chromeOptions.add_experimental_option('prefs', prefs)
    chromedriver_path = os.path.join(BASE_PATH, 'utils/driver/chromedriver')
    log_path = os.path.join(BASE_PATH, 'utils/driver/test.log')
    self.driver = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=chromeOptions, service_log_path=log_path)
Selfjustifying answered 29/5, 2019 at 10:54 Comment(0)
E
1

We just found a different approach that allows us to enable geolocation on chrome (currently 65.0.3325.181 (Build officiel) (64 bits)) without mocking the native javascript function.

The idea is to authorize the current site (represented by BaseUrls.Root.AbsoluteUri) to access to geolocation information.

public static void UseChromeDriver(string lang = null)
{
    var options = new ChromeOptions();
    options.AddArguments(
       "--disable-plugins",   
       "--no-experiments", 
       "--disk-cache-dir=null");

    var geolocationPref = new JObject(
        new JProperty(
            BaseUrls.Root.AbsoluteUri,
            new JObject(
                new JProperty("last_modified", "13160237885099795"),
                new JProperty("setting", "1")
            )
        )
     );

  options.AddUserProfilePreference(
      "content_settings.exceptions.geolocation", 
       geolocationPref);

    WebDriver = UseDriver<ChromeDriver>(options);
}

private static TWebDriver UseDriver<TWebDriver>(DriverOptions aDriverOptions)
    where TWebDriver : RemoteWebDriver
{
    Guard.RequiresNotNull(aDriverOptions, nameof(UITestsContext), nameof(aDriverOptions));

    var webDriver = (TWebDriver)Activator.CreateInstance(typeof(TWebDriver), aDriverOptions);
    Guard.EnsuresNotNull(webDriver, nameof(UITestsContext), nameof(WebDriver));

    webDriver.Manage().Window.Maximize();
    webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
    webDriver.NavigateToHome();

    return webDriver;
}
Eigenfunction answered 5/4, 2018 at 11:47 Comment(0)
M
1
ChromeOptions options = new ChromeOptions();
    HashMap<String, Integer> contentSettings = new HashMap<String, Integer>();
    HashMap<String, Object> profile = new HashMap<String, Object>();
    HashMap<String, Object> prefs = new HashMap<String, Object>();

    contentSettings.put("geolocation", 1);
    contentSettings.put("notifications", 2);
    profile.put("managed_default_content_settings", contentSettings);
    prefs.put("profile", profile);
    options.setExperimentalOption("prefs", prefs);
Magnifico answered 25/8, 2021 at 12:51 Comment(1)
This code not working.Draw
E
0

The simplest to set geoLocation is to just naviaget on that url and click on allow location by selenium. Here is the code for refrence

 driver.navigate().to("chrome://settings/content");
    driver.switchTo().frame("settings");
    WebElement location= driver.findElement(By.xpath("//*[@name='location' and @value='allow']"));
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ((JavascriptExecutor) driver).executeScript("arguments[0].click();", location);
     WebElement done= driver.findElement(By.xpath(""));

    driver.findElement(By.xpath("//*[@id='content-settings-overlay-confirm']")).click();

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    driver.navigate().to("url");
Elongation answered 11/3, 2016 at 11:28 Comment(0)
M
0

Cypress:

I encountered with same problem but mocking was not worked for me. My case: Application use geo location for the login purpose. So with mock it not worked for me.

Solution: I used below package and followed the steps and its works for me.

https://www.npmjs.com/package/cypress-visit-with-custom-geolocation

Working sample example: https://github.com/gaikwadamolraj/cypress-visit-with-custom-geolocation

Mastodon answered 22/3, 2022 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.