如何在 chromedriver 中启用地理位置支持?

How do I enable geolocation support in chromedriver?

提问人:Thomas Keller 提问时间:12/7/2011 最后编辑:aloisdgThomas Keller 更新时间:3/22/2022 访问量:23654

问:

我需要使用 Selenium 测试 JS 地理定位功能,并且我正在使用 chromedriver 在最新的 Chrome 上运行测试。

现在的问题是 Chrome 在测试期间提示我启用地理位置,并且我不知道如何在运行时单击那个小栏,所以我正在拼命寻找一种方法来启动 chromedriver 和 chrome,并带有一些选项或触发器来默认启用此功能。然而,我在这里能找到的只是如何完全禁用地理定位。

我该如何解决这个问题?

地理定位

评论


答:

3赞 Sotomajor 12/22/2011 #1

在Firefox中对我有用的方法是首先手动访问该站点,授予这些权限,然后将firefox配置文件复制到外部的某个地方,并使用该配置文件创建selenium firefox实例。

所以:

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

  2. 创建FF实例:

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

我很确定类似的东西应该适用于 Chrome。虽然配置文件加载的api有点不同。你可以在这里检查:http://code.google.com/p/selenium/wiki/ChromeDriver

评论

0赞 Thomas Keller 12/27/2011
感谢您的有用提示,这并不完全是我想要的(因为我加载到的 URL 的主机部分可能会随着时间的推移而改变,我每次都必须更新配置文件或提供不同的配置文件),但总比现在没有好。
3赞 Tomasz Borowski 1/5/2012 #2

以下是我如何用水豚进行黄瓜测试

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

并且有指向其他有用的配置文件设置的链接:pref_names.cc

看看 RubyBindings 中的 “Tweaking profile preferences”

18赞 redochka 4/3/2012 #3

chromedriver wiki 的已知问题部分,他们说您无法指定自定义配置文件

这就是为什么在我看来,@Sotomajor关于在 Chrome 中使用配置文件就像使用 firefox 一样的答案是行不通的。

在我的一次集成测试中,我遇到了同样的问题。但是因为我不关心真实的地理位置值,所以我所要做的就是模拟 window.navigator.gelocation

在您的 java 测试代码中,请放置此解决方法以避免 Chrome geoloc 权限信息栏。

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

这里的纬度 (555) 和经度 (999) 值只是测试值

评论

0赞 Meglio 10/29/2017
返回的值应为标量数,而不是字符串。
0赞 Nic Laforge 5/30/2019
只是要指出,同样的 JS 可以在 Safari/Chrome 上运行
2赞 tbsalling 4/9/2013 #4

至于你最初的问题:

您应该手动启动Firefox一次 - 然后选择用于Selenium的配置文件。

输入地址行;找到主机的名称 - 然后选择 。about:permissionsshare location : "allow"

就这样。现在,您的 Selenium 测试用例将看不到不在 DOM 中的可怕浏览器对话框。

0赞 Niraj Singh 3/11/2016 #5

设置 geoLocation 的最简单方法是在该 url 上导航并单击 allow location by selenium。这是 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");
1赞 j_freyre 4/5/2018 #6

我们刚刚找到了一种不同的方法,允许我们在 chrome(当前为 65.0.3325.181(构建官方)(64 位))上启用地理定位,而无需模拟本机 javascript 函数。

这个想法是授权当前站点(由 表示)访问地理位置信息。BaseUrls.Root.AbsoluteUri

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;
}
2赞 ESing 5/29/2019 #7

我采用了你的方法,但它不起作用。我在 Chrome 的首选项配置中没有找到“BaseUrls.Root.AbsoluteUri”。并使用脚本进行测试

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)
1赞 Bibhu Ptr 8/25/2021 #8
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);

评论

0赞 Martin Ma 3/12/2022
此代码不起作用。
0赞 Amol Gaikwad 3/22/2022 #9

柏树:

我遇到了同样的问题,但嘲笑对我不起作用。 我的情况: 应用程序使用地理位置进行登录。所以用模拟它对我不起作用。

溶液: 我使用了下面的软件包,并按照步骤及其对我的工作方式进行操作。

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

工作示例:https://github.com/gaikwadamolraj/cypress-visit-with-custom-geolocation