How do I enable geolocation support in chromedriver?

前端 未结 7 623
日久生厌
日久生厌 2020-11-30 08:08

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

7条回答
  •  伪装坚强ぢ
    2020-11-30 08:47

    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(options);
    }
    
    private static TWebDriver UseDriver(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;
    }
    

提交回复
热议问题