How do I enable geolocation support in chromedriver?

眉间皱痕 提交于 2019-11-27 04:39:57

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

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

Tomasz Borowski

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

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.

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");

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

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': "\"11.111698@-122.222954:\"",
        },
        '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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!