Java Code Examples for org.openqa.selenium.chrome.ChromeOptions

The following are top voted examples for showing how to use org.openqa.selenium.chrome.ChromeOptions. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alex   File: ChromeDriverConfig.java   View source code 12 votes vote down vote up
@Override
public WebDriver createDriver() throws Exception {
    final ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--no-sandbox");
    if (headless) {
        chromeOptions.setHeadless(true);
    }

    final Map<String, String> environmentVariables = new HashMap<>();
    if (!headless && xvfbPort != null) {
        environmentVariables.put("DISPLAY", ":" + String.valueOf(xvfbPort));
    }

    final ChromeDriverService service = new ChromeDriverService.Builder()
            .usingAnyFreePort()
            .withEnvironment(environmentVariables)
            .build();

    final WebDriver driver = new ChromeDriver(service, chromeOptions);
    manage(driver);

    return driver;
}
 
Example 2
Project: teasy   File: SeleniumTestExecutionListener.java   View source code 7 votes vote down vote up
private DesiredCapabilities getChromeDesiredCapabilities(Settings settings) {
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        //Added to avoid yellow warning in chrome 35
        ChromeOptions options = new ChromeOptions();
//        options.addArguments("test-type");
        //For view pdf in chrome
        options.setExperimentalOption("excludeSwitches", Arrays.asList("test-type", "--ignore-certificate-errors"));

        if (settings.isHeadlessBrowser()) {
            options.addArguments("headless");
        }

        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setPlatform(Platform.WINDOWS);
        setAlertBehaviorCapabilities(capabilities);
        setLoggingPrefs(capabilities);
        setProxy(capabilities);
        return capabilities;
    }
 
Example 3
Project: NoraUi   File: DriverFactory.java   View source code 7 votes vote down vote up
/**
 * Sets the target browser binary path in chromeOptions if it exists in configuration.
 *
 * @param capabilities
 *            The global DesiredCapabilities
 */
private void setChromeOptions(final DesiredCapabilities capabilities, ChromeOptions chromeOptions) {

    // Set custom downloaded file path. When you check content of downloaded file by robot.
    HashMap<String, Object> chromePrefs = new HashMap<>();
    chromePrefs.put("download.default_directory", System.getProperty("user.dir") + File.separator + "downloadFiles");
    chromeOptions.setExperimentalOption("prefs", chromePrefs);

    // Set custom chromium (if you not use default chromium on your target device)
    String targetBrowserBinaryPath = Context.getWebdriversProperties("targetBrowserBinaryPath");
    if (targetBrowserBinaryPath != null && !"".equals(targetBrowserBinaryPath)) {
        chromeOptions.setBinary(targetBrowserBinaryPath);
    }

    capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
}
 
Example 4
Project: givemeadriver   File: ChromeCapabilitiesConverterTest.java   View source code 7 votes vote down vote up
@Test
public void notSettingAnyProperty() {
    // given
    WebDriverProperties properties = new WebDriverProperties();

    // when
    Capabilities convertedCapabilities = chromeCapabilitiesConverter.convert(properties);

    // then
    // expected chrome capabilities
    ChromeOptions expectedChromeOptions = new ChromeOptions();
    expectedChromeOptions.setCapability(CAPABILITY_BROWSER_NAME, "chrome");
    expectedChromeOptions.setCapability(CAPABILITY_AUTOCLOSE, false);

    expectedChromeOptions.addArguments("--disable-device-discovery-notifications");
    expectedChromeOptions.addArguments("--disable-infobars");

    assertThat(convertedCapabilities.asMap()).isEqualTo(expectedChromeOptions.asMap());
    assertThat(convertedCapabilities).isEqualTo(expectedChromeOptions);
}
 
Example 5
Project: che   File: SeleniumWebDriver.java   View source code 7 votes vote down vote up
private RemoteWebDriver doCreateDriver(URL webDriverUrl) {
  DesiredCapabilities capability;

  switch (browser) {
    case GOOGLE_CHROME:
      ChromeOptions options = new ChromeOptions();
      options.addArguments("--no-sandbox");
      options.addArguments("--dns-prefetch-disable");

      capability = DesiredCapabilities.chrome();
      capability.setCapability(ChromeOptions.CAPABILITY, options);
      break;

    default:
      capability = DesiredCapabilities.firefox();
      capability.setCapability("dom.max_script_run_time", 240);
      capability.setCapability("dom.max_chrome_script_run_time", 240);
  }

  RemoteWebDriver driver = new RemoteWebDriver(webDriverUrl, capability);
  driver.manage().window().setSize(new Dimension(1920, 1080));

  return driver;
}
 
Example 6
Project: spa-perf   File: SPAPerfChromeDriver.java   View source code 7 votes vote down vote up
private static DesiredCapabilities getPerformanceLoggingCapabilities() {
    DesiredCapabilities caps = DesiredCapabilities.chrome();

    // Enable performance logging
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

    // Enable timeline tracing
    Map<String, Object> chromeOptions = new HashMap<String, Object>();
    Map<String, String> perfLoggingPrefs = new HashMap<String, String>();
    // Tracing categories, please note NO SPACE NEEDED after the commas
    perfLoggingPrefs.put("traceCategories", "blink.console,disabled-by-default-devtools.timeline");
    chromeOptions.put("perfLoggingPrefs", perfLoggingPrefs);
    //chromeOptions.put("debuggerAddress", "127.0.0.1:10134");
    caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

    return caps;
}
 
Example 7
Project: webDriverExperiments   File: AaarghFirefoxWhyDostThouMockMe.java   View source code 7 votes vote down vote up
@Test
public void simpleUserInteractionInGoogleChrome(){
    String currentDir = System.getProperty("user.dir");

    // amend this for your location of chromedriver
    String chromeDriverLocation = currentDir + "/../tools/chromedriver/chromedriver.exe";
    System.setProperty("webdriver.chrome.driver", chromeDriverLocation);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("disable-plugins");
    options.addArguments("disable-extensions");

    driver = new ChromeDriver(options);

    checkSimpleCtrlBInteractionWorks();
}
 
Example 8
Project: NaukriSite   File: Setup.java   View source code 6 votes vote down vote up
@BeforeMethod
public void siteUp () {

	final String exe = "chromedriver.exe";
	final String path = getClass ().getClassLoader ()
		.getResource (exe)
		.getPath ();
	final String webSite = "http://www.naukri.com";
	final String binaryPath = "C:\\Users\\DELL\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";
	
	System.setProperty("webdriver.chrome.driver", path);
	ChromeOptions chromeOpt= new ChromeOptions();
	chromeOpt.setBinary(binaryPath);
	
	driver = new ChromeDriver (chromeOpt);
	driver.get(webSite);
	driver.manage ().timeouts ().implicitlyWait (10, TimeUnit.SECONDS);
	driver.manage().window().maximize();
	windowHandling ();
}
 
Example 9
Project: givemeadriver   File: ChromeCapabilitiesConverterTest.java   View source code 6 votes vote down vote up
@Test
public void settingAllChromeProperties() throws IOException {
    // given
    WebDriverProperties properties = new WebDriverProperties();
    properties.setProperty("device", IPHONE_DEVICE);
    properties.setProperty("userAgent", ANY_USER_AGENT);
    properties.setProperty("viewportSize", "378x664");
    properties.setProperty("pixelRatio", "3.0");
    properties.setProperty("headless", "true");

    // when
    Capabilities convertedCapabilities = chromeCapabilitiesConverter.convert(properties);

    // then
    // expected chrome options
    ChromeOptions expectedChromeOptions = new ChromeOptions();
    expectedChromeOptions.setCapability(CAPABILITY_BROWSER_NAME, "chrome");
    expectedChromeOptions.setCapability(CAPABILITY_AUTOCLOSE, false);
    Map<String, Object> expectedMobileEmulation = new HashMap<>();
    Map<String, Object> expectedDeviceMetrics = new HashMap<>();
    expectedDeviceMetrics.put("width", 378);
    expectedDeviceMetrics.put("height", 664);
    expectedDeviceMetrics.put(CAPABILITY_PIXEL_RATIO, 3.0);
    expectedMobileEmulation.put("deviceMetrics", expectedDeviceMetrics);
    expectedMobileEmulation.put(CAPABILITY_DEVICE_NAME, IPHONE_DEVICE);
    expectedMobileEmulation.put(CAPABILITY_USER_AGENT, ANY_USER_AGENT);
    expectedChromeOptions.setExperimentalOption("mobileEmulation", expectedMobileEmulation);
    expectedChromeOptions.addArguments("--disable-device-discovery-notifications");
    expectedChromeOptions.addArguments("--disable-infobars");
    expectedChromeOptions.addArguments("--headless", "--disable-gpu");

    assertThat(convertedCapabilities.asMap()).isEqualTo(expectedChromeOptions.asMap());
}
 
Example 10
Project: givemeadriver   File: ChromeCapabilitiesConverterTest.java   View source code 6 votes vote down vote up
@Test
public void notSettingDeviceMetrics() throws IOException {
    // given
    WebDriverProperties properties = new WebDriverProperties();
    properties.setProperty("device", IPHONE_DEVICE);
    properties.setProperty("userAgent", ANY_USER_AGENT);

    // when
    Capabilities convertedCapabilities = chromeCapabilitiesConverter.convert(properties);

    // then
    // expected chrome options
    ChromeOptions expectedChromeOptions = new ChromeOptions();
    Map<String, Object> expectedMobileEmulation = new HashMap<>();
    expectedChromeOptions.setCapability(CAPABILITY_BROWSER_NAME, "chrome");
    expectedChromeOptions.setCapability(CAPABILITY_AUTOCLOSE, false);
    expectedMobileEmulation.put(CAPABILITY_DEVICE_NAME, IPHONE_DEVICE);
    expectedMobileEmulation.put(CAPABILITY_USER_AGENT, ANY_USER_AGENT);
    expectedChromeOptions.setExperimentalOption("mobileEmulation", expectedMobileEmulation);
    expectedChromeOptions.addArguments("--disable-device-discovery-notifications");
    expectedChromeOptions.addArguments("--disable-infobars");

    assertThat(convertedCapabilities.asMap()).isEqualTo(expectedChromeOptions.asMap());
}
 
Example 11
Project: akita-testing-template   File: AkitaChromeDriverProvider.java   View source code 6 votes vote down vote up
@Override
public WebDriver createDriver(DesiredCapabilities capabilities) {
    Map<String, Object> preferences = new Hashtable<>();
    preferences.put("profile.default_content_settings.popups", 0);
    preferences.put("download.prompt_for_download", "false");
    String downloadsPath = System.getProperty("user.home") + "/Downloads";
    preferences.put("download.default_directory", loadSystemPropertyOrDefault("fileDownloadPath", downloadsPath));
    preferences.put("plugins.plugins_disabled", new String[]{
            "Adobe Flash Player", "Chrome PDF Viewer"});
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", preferences);

    capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    return new ChromeDriver(capabilities);
}
 
Example 12
Project: selenium-jupiter   File: ChromeDriverHandler.java   View source code 6 votes vote down vote up
@Override
public void resolve() {
    try {
        Optional<Object> testInstance = context.getTestInstance();
        Optional<Capabilities> capabilities = annotationsReader
                .getCapabilities(parameter, testInstance);
        ChromeOptions chromeOptions = (ChromeOptions) getOptions(parameter,
                testInstance);

        if (capabilities.isPresent()) {
            chromeOptions.merge(capabilities.get());
        }

        object = new ChromeDriver(chromeOptions);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 13
Project: hippo   File: WebDriverProvider.java   View source code 6 votes vote down vote up
/**
 * Initialises the WebDriver (client).
 *
 * This method should be called once before each test to ensure that the session state doesn't bleed from one test
 * to another (such as user being logged in).
 */
public void initialise() {

    final ChromeOptions chromeOptions = new ChromeOptions();

    final Map<String, Object> chromePrefs = new HashMap<>();
    log.info("Setting WebDriver download directory to '{}'.", downloadDirectory);
    chromePrefs.put("download.default_directory", downloadDirectory.toAbsolutePath().toString());

    chromeOptions.setExperimentalOption("prefs", chromePrefs);
    log.info("Configuring WebDriver to run in {} mode.", isHeadlessMode ? "headless" : "full, graphical");
    if (isHeadlessMode) {
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("window-size=1920,1080");
    }

    webDriver = new RemoteWebDriver(webDriverServiceProvider.getUrl(), chromeOptions);
}
 
Example 14
Project: Bytecoder   File: BytecoderUnitTestRunner.java   View source code 6 votes vote down vote up
private WebDriver newDriverForTest() {
    ChromeOptions theOptions = new ChromeOptions();
    theOptions.addArguments("headless");
    theOptions.addArguments("disable-gpu");

    LoggingPreferences theLoggingPreferences = new LoggingPreferences();
    theLoggingPreferences.enable(LogType.BROWSER, Level.ALL);
    theOptions.setCapability(CapabilityType.LOGGING_PREFS, theLoggingPreferences);

    DesiredCapabilities theCapabilities = DesiredCapabilities.chrome();
    theCapabilities.setCapability(ChromeOptions.CAPABILITY, theOptions);

    return new RemoteWebDriver(DRIVERSERVICE.getUrl(), theCapabilities);
}
 
Example 15
Project: akita   File: MobileChrome.java   View source code 6 votes vote down vote up
/**
 * Создание instance google chrome эмулирующего работу на мобильном устройстве (по умолчанию nexus 5)
 * Мобильное устройство может быть задано через системные переменные
 *
 * @param capabilities настройки Chrome браузера
 * @return возвращает новый instance Chrome драйера
 */

@Override
public WebDriver createDriver(DesiredCapabilities capabilities) {
    log.info("---------------run CustomMobileDriver---------------------");
    String mobileDeviceName = loadSystemPropertyOrDefault("device", "Nexus 5");
    Map<String, String> mobileEmulation = new HashMap<>();
    mobileEmulation.put("deviceName", mobileDeviceName);

    Map<String, Object> chromeOptions = new HashMap<>();
    chromeOptions.put("mobileEmulation", mobileEmulation);

    DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
    desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
    desiredCapabilities.setBrowserName(desiredCapabilities.chrome().getBrowserName());
    return new ChromeDriver(desiredCapabilities);
}
 
Example 16
Project: f4f-tts   File: ScrapperTtsUpdater.java   View source code 6 votes vote down vote up
private ChromeDriver setUp(Properties properties) {
    System.setProperty("webdriver.chrome.driver", properties.getProperty("webdriver.chrome.driver"));
    String binaryPath = properties.getProperty(CHROME_DRIVER_BINARY_PATH);

    if (binaryPath == null) {
        throw new RuntimeException("Missing property : " + CHROME_DRIVER_BINARY_PATH);
    }

    Map<String, Object> prefs = new HashMap<>();
    prefs.put("profile.default_content_setting_values.notifications", 2);
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", prefs);
    options.setBinary(binaryPath);
    options.addArguments("--headless");
    options.addArguments("--user-agent=" + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
    return new ChromeDriver(options);
}
 
Example 17
Project: alimama   File: Test.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {

		/*ChromeDriverService service = new ChromeDriverService.Builder()
				.usingDriverExecutable(
						new File("f:\\app\\chromedriver\\chromedriver.exe"))
				.usingAnyFreePort().build();
		service.start();*/
		
		ChromeOptions options = new ChromeOptions();
		//options.addArguments(“–user-data-dir=C:/Users/xxx/AppData/Local/Google/Chrome/User Data/Default”);
		String userDateDir = "C:/Users/ThinkPad/AppData/Local/Google/Chrome/User Data";
		options.addArguments("--user-data-dir="+userDateDir);
		// 璁剧疆璁块棶ChromeDriver鐨勮矾寰�
		System.setProperty("webdriver.chrome.driver", "f:\\app\\chromedriver\\chromedriver.exe");
		WebDriver driver = new ChromeDriver(options);
		driver.get("http://www.baidu.com/");

		
	}
 
Example 18
Project: jwebrobot   File: WebDriverProvider.java   View source code 6 votes vote down vote up
public WebDriver createInstance(Type type) {
    switch (type) {
        case CHROME:
            return new ChromeDriver();
        case CHROME_HEADLESS:
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--headless", "--disable-gpu");
            ChromeDriver chromeDriver = new ChromeDriver(options);

            return chromeDriver;
        case OPERA:
            return new OperaDriver(getOperaCapabilities());
        case FIREFOX:
        default:
            return new FirefoxDriver();
    }
}
 
Example 19
Project: dawg   File: BrowserServiceManager.java   View source code 6 votes vote down vote up
/**
 * Provides the browser desired capabilities.
 *
 * @param browser
 *        Browser for which the desired capabilities to be returned.
 * @return Capabilities corresponding to the browser passed.
 */
private static Capabilities getDesiredBrowserCapabilities(Browser browser) {
    DesiredCapabilities capabilities = null;
    switch (browser) {
        case chrome:
            ChromeOptions options = new ChromeOptions();
            options.addArguments(CHROME_OPTION_ARGUMENTS);
            capabilities = DesiredCapabilities.chrome();
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            break;
        default:
            capabilities = new DesiredCapabilities();
            break;
    }
    return capabilities;
}
 
Example 20
Project: AndroidRobot   File: ChromeDriverClient.java   View source code 6 votes vote down vote up
public void createDriver(String pkg_name, String sn) {
    	if(this.driver == null) {
	        ChromeOptions chromeOptions = new ChromeOptions();
	        chromeOptions.setExperimentalOption("androidPackage", pkg_name);
	//        chromeOptions.setExperimentalOption("androidActivity", "com.eg.android.AlipayGphone.AlipayLogin");
	//        chromeOptions.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
	        chromeOptions.setExperimentalOption("androidUseRunningApp", true);
	        chromeOptions.setExperimentalOption("androidDeviceSerial", sn);
	//        Map<String, Object> chromeOptions = new HashMap<String, Object>();
	//        chromeOptions.put("androidPackage", "com.eg.android.AlipayGphoneRC");
	//        chromeOptions.put("androidActivity", "com.eg.android.AlipayGphone.AlipayLogin");
	        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
	        LoggingPreferences logPrefs = new LoggingPreferences();
	        logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
	        capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
	        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
//	        capabilities.setCapability(CapabilityType., value);
	        if(ChromeService.getService() != null)
	        	driver = new RobotRemoteWebDriver(ChromeService.getService().getUrl(), capabilities);
    	}
    }
 
Example 21
Project: AugmentedDriver   File: YamlCapabilitiesConverter.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static DesiredCapabilities convert(Path yamlFile) throws YamlException {
    Preconditions.checkNotNull(yamlFile);
    Preconditions.checkArgument(Files.exists(yamlFile));
    try {
        YamlReader yamlReader = new YamlReader(new FileReader(yamlFile.toFile()));
        Map<String, String> properties = (Map<String, String>) yamlReader.read();
        if (properties == null || properties.isEmpty()) {
            throw new IllegalArgumentException(String.format("File %s is empty", yamlFile));
        }
        if (!properties.containsKey(CAPABILITIES)) {
            throw new IllegalArgumentException(String.format("File %s should have property capabilities, got %s", yamlFile, properties));
        }
        DesiredCapabilities capabilities = Capabilities.valueOf(properties.remove(CAPABILITIES).toUpperCase()).getCapabilities();
        properties.entrySet()
                .stream()
                .forEach(pair -> capabilities.setCapability(pair.getKey(), pair.getValue()));

        if (properties.containsKey(CHROME_EXTENSION)) {
            ChromeOptions options = new ChromeOptions();
            options.addExtensions(new File(properties.get(CHROME_EXTENSION)));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        }
        return capabilities;
    } catch (FileNotFoundException e) {
        // This should never happen
        throw new IllegalStateException(e);
    }
}
 
Example 22
Project: frameworkium-core   File: ChromeImpl.java   View source code 6 votes vote down vote up
@Override
public ChromeOptions getCapabilities() {
    ChromeOptions chromeOptions = new ChromeOptions();
    // useful defaults
    chromeOptions.setCapability(
            "chrome.switches",
            singletonList("--no-default-browser-check"));
    chromeOptions.setCapability(
            "chrome.prefs",
            ImmutableMap.of("profile.password_manager_enabled", "false"));

    // Use Chrome's built in device emulators
    if (Property.DEVICE.isSpecified()) {
        chromeOptions.setExperimentalOption(
                "mobileEmulation",
                ImmutableMap.of("deviceName", Property.DEVICE.getValue()));
    }

    // Allow user to provide their own user directory, for custom chrome profiles
    if (Property.CHROME_USER_DATA_DIR.isSpecified()) {
        chromeOptions.addArguments(
                "user-data-dir=" + Property.CHROME_USER_DATA_DIR.getValue());
    }
    chromeOptions.setHeadless(Property.HEADLESS.getBoolean());
    return chromeOptions;
}
 
Example 23
Project: BRAP   File: Browser.java   View source code 6 votes vote down vote up
public void openBrowser(String url,String type,String browserBin,String profile) {
	try {
		if(type.toLowerCase().contains("chrome")){
			ChromeOptions options = new ChromeOptions();
			options.addArguments("test-type");
			if(profile!=null){
				options.addArguments("user-data-dir="
						+ profile);
			}
			System.setProperty("webdriver.chrome.driver",browserBin );
			webDriver = (RemoteWebDriver) new ChromeDriver(options);
		}else if(type.toLowerCase().contains("firefox")){
			webDriver = new FirefoxDriver();
		}
		webDriver.get(url);
	} catch (Exception e) {
	}

}
 
Example 24
Project: selenium-utils   File: RemoteBuildr.java   View source code 6 votes vote down vote up
public RemoteWebDriver build() {
    DesiredCapabilities capabilities;

    if (browsr==null || Browsr.Firefox.equals(browsr)) {
        capabilities = DesiredCapabilities.firefox();
        FirefoxProfile profile = FirefoxBuildr.createFirefoxProfile(locales);
        capabilities.setCapability(FirefoxDriver.PROFILE, profile);
    } else {
        capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, ChromeBuildr.createChromeOptions(locales));
    }
    try {
        return new RemoteWebDriver(new URL(hubUrl), capabilities);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 25
Project: knorxx   File: SimpleWebPageGT.java   View source code 6 votes vote down vote up
@Test
  public void heading() {
      ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=800,600");
 
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
      
      driver.get("http://localhost:8080/generator-spring-sample-app/knorxx/page/SimpleWebPage.html");
      
      WebDriverWait wait = new WebDriverWait(driver, 10);
      wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id(SimpleWebPage.TITLE_ID.substring(1)), SimpleWebPage.HEADING));        
      
      driver.quit();
  }
 
Example 26
Project: webDriverExperiments   File: AaarghFirefoxWhyDostThouMockMe.java   View source code 6 votes vote down vote up
@Test
public void simpleUserInteractionInGoogleChrome(){
    String currentDir = System.getProperty("user.dir");

    // amend this for your location of chromedriver
    String chromeDriverLocation = currentDir + "/../tools/chromedriver/chromedriver.exe";
    System.setProperty("webdriver.chrome.driver", chromeDriverLocation);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("disable-plugins");
    options.addArguments("disable-extensions");

    driver = new ChromeDriver(options);

    checkSimpleCtrlBInteractionWorks();
}
 
Example 27
Project: automation-test-engine   File: MyChromeDriver.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public WebDriver getWebDriverInstance() {
	WebDriver retVal = getWebDriver();
	if (null == retVal) {
		setChromeDriverSystemEnv();
		ChromeOptions ops = new ChromeOptions();
		ops.addArguments(getBrowserProfile().getStartArguments());
		if (getBrowserProfile().isPreserveCookiesOnExecutions()) {

			ops.addArguments("--user-data-dir="
					+ getBrowserProfile().getTestCaseChromeUserDataDir());

		}

		retVal = new ChromeDriver(ops);

		setWebDriver(retVal);
	}
	return retVal;

}
 
Example 28
Project: crawljax   File: WebDriverBrowserBuilder.java   View source code 6 votes vote down vote up
private EmbeddedBrowser newChromeBrowser(ImmutableSortedSet<String> filterAttributes,
        long crawlWaitReload, long crawlWaitEvent) {
	ChromeDriver driverChrome;
	if (configuration.getProxyConfiguration() != null
	        && configuration.getProxyConfiguration().getType() != ProxyType.NOTHING) {
		ChromeOptions optionsChrome = new ChromeOptions();
		String lang = configuration.getBrowserConfig().getLangOrNull();
		if (!Strings.isNullOrEmpty(lang)) {
			optionsChrome.setExperimentalOptions("intl.accept_languages", lang);
		}
		optionsChrome.addArguments("--proxy-server=http://"
		        + configuration.getProxyConfiguration().getHostname() + ":"
		        + configuration.getProxyConfiguration().getPort());
		driverChrome = new ChromeDriver(optionsChrome);
	} else {
		driverChrome = new ChromeDriver();
	}

	return WebDriverBackedEmbeddedBrowser.withDriver(driverChrome, filterAttributes,
	        crawlWaitEvent, crawlWaitReload);
}
 
Example 29
Project: seletest   File: ConfigurationDriver.java   View source code 6 votes vote down vote up
/**
 * Load chrome options from properties file
 * @param optionsPath String path to prprties file that stored the chrome options
 * @return ChromeOptions the chrome options loaded from properties file
 * @throws Exception
 */
public ChromeOptions chromeOptions(String optionsPath) throws Exception{
    ChromeOptions options=new ChromeOptions();
    Properties configProp = new Properties();
    configProp.load(new FileReader(optionsPath));
    Enumeration<?> keys = configProp.propertyNames();
    while(keys.hasMoreElements()){
        String key = (String)keys.nextElement();
        String value = (String) configProp.get(key);
        if(!value.isEmpty()){
            options.addArguments(key+"="+value);
        } else {
            options.addArguments(key);
        }
    }
    return options;
}
 
Example 30
Project: robotframework-seleniumlibrary-java   File: BrowserManagement.java   View source code 6 votes vote down vote up
protected void parseBrowserOptionsChrome(String browserOptions, DesiredCapabilities desiredCapabilities) {
    if (browserOptions != null && !"NONE".equalsIgnoreCase(browserOptions)) {
        JSONObject jsonObject = (JSONObject) JSONValue.parse(browserOptions);
        if (jsonObject != null) {
            Map<String, Object> chromeOptions = new HashMap<String, Object>();
            Iterator<?> iterator = jsonObject.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
                String key = entry.getKey().toString();
                logging.debug(String.format("Adding property: %s with value: %s (type: %s)",
                        key.toString(), entry.getValue(), entry.getValue().getClass()));
                chromeOptions.put(key, entry.getValue());
            }
            desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        } else {
            logging.warn("Invalid browserOptions: " + browserOptions);
        }
    }
}
 
Example 31
Project: chrome-extension-selenium-example   File: RemoteDriverConfig.java   View source code 6 votes vote down vote up
/**
 * Here you can add your capabilities you want to use.
 *
 * @see https://code.google.com/p/chromedriver/wiki/CapabilitiesAndSwitches#List_of_recognized_capabilities
 */
protected void buildDesiredCapabilities() {
	DesiredCapabilities capabilities = createDesiredCapabilitiesForChrome();

	// get Platform from environment
	String platformString = System.getenv("PLATFORM");
	if (platformString == null) {
		platformString = Platform.WINDOWS.toString();
	}
	Platform platform = Platform.valueOf(platformString);
	capabilities.setCapability("platform", platform);

	// set browser version
	String versionString = System.getenv("VERSION");
	if (versionString != null) {
		capabilities.setVersion("38");
	}

	// if chrome options are not build yet, we have to handle it
	if (chromeOptions == null) {
		buildChromeOptions();
	}
	capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

	this.desiredCapabilities = capabilities;
}
 
Example 32
Project: carina   File: ChromeCapabilities.java   View source code 6 votes vote down vote up
public DesiredCapabilities getCapability(String testName)
{
	DesiredCapabilities capabilities = new DesiredCapabilities();
	capabilities = initBaseCapabilities(capabilities, BrowserType.CHROME, testName);
	capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized", "--ignore-ssl-errors"));
	capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
	capabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, false);

	ChromeOptions options = new ChromeOptions();
	options.addArguments("test-type");

	if (Configuration.getBoolean(Configuration.Parameter.AUTO_DOWNLOAD))
	{
		HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
		chromePrefs.put("download.prompt_for_download", false);
		chromePrefs.put("download.default_directory", ReportContext.getArtifactsFolder().getAbsolutePath());
		chromePrefs.put("plugins.always_open_pdf_externally", true);
		options.setExperimentalOption("prefs", chromePrefs);
	}

	capabilities.setCapability(ChromeOptions.CAPABILITY, options);
	return capabilities;
}
 
Example 33
Project: jspider   File: ChromeDesiredCapabilities.java   View source code 5 votes vote down vote up
public ChromeDesiredCapabilities() {
    super(BrowserType.ANDROID, "", Platform.ANDROID);

    prefs = new HashMap<String, Object>();
    options = new ChromeOptions();
    options.setExperimentalOption("prefs", prefs);
    setCapability(ChromeOptions.CAPABILITY, options);
}
 
Example 34
Project: qaa-amazon   File: Chrome.java   View source code 5 votes vote down vote up
@Override
public Capabilities configuration(final XmlConfig config) {
    final ChromeOptions options = new ChromeOptions();
    options.setCapability("enableVNC", true);
    options.setCapability("enableVideo", true);
    options.setCapability("name", config.getTestName());
    options.setCapability("screenResolution", "1280x1024x24");
    return merge(config, options);
}
 
Example 35
Project: autotest   File: WebTestBase.java   View source code 5 votes vote down vote up
@BeforeEach
void init() {
    //打开chrome浏览器
    System.setProperty("webdriver.chrome.driver", Thread.currentThread().getContextClassLoader()
            .getResource("autotest/" + "chromedriver.exe").getPath());
    ChromeOptions options = new ChromeOptions();
    options.addArguments("disable-infobars");
    d = new ChromeDriver(options);
    d.manage().window().maximize();
    d.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
 
Example 36
Project: lambda-selenium   File: LambdaWebDriverFactory.java   View source code 5 votes vote down vote up
private ChromeOptions getLambdaChromeOptions() {
    ChromeOptions options = new ChromeOptions();
    options.setBinary(getLibLocation("chrome"));
    options.addArguments("--disable-gpu");
    options.addArguments("--headless");
    options.addArguments("--window-size=1366,768");
    options.addArguments("--single-process");
    options.addArguments("--no-sandbox");
    options.addArguments("--user-data-dir=/tmp/user-data");
    options.addArguments("--data-path=/tmp/data-path");
    options.addArguments("--homedir=/tmp");
    options.addArguments("--disk-cache-dir=/tmp/cache-dir");
    return options;
}
 
Example 37
Project: NoraUi   File: DriverFactory.java   View source code 5 votes vote down vote up
/**
 * Generates a chrome webdriver.
 *
 * @param headlessMode
 *            Enable headless mode ?
 * @return
 *         A chrome webdriver
 * @throws TechnicalException
 *             if an error occured when Webdriver setExecutable to true.
 */
private WebDriver generateGoogleChromeDriver(boolean headlessMode) throws TechnicalException {
    final String pathWebdriver = DriverFactory.getPath(Driver.CHROME);
    if (!new File(pathWebdriver).setExecutable(true)) {
        throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE));
    }
    logger.info("Generating Chrome driver ({}) ...", pathWebdriver);

    System.setProperty(Driver.CHROME.getDriverName(), pathWebdriver);

    final ChromeOptions chromeOptions = new ChromeOptions();
    final DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
    capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);

    setLoggingLevel(capabilities);

    if (Context.isHeadless()) {
        chromeOptions.addArguments("--headless");
    }

    // Proxy configuration
    if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) {
        capabilities.setCapability(CapabilityType.PROXY, Context.getProxy());
    }

    setChromeOptions(capabilities, chromeOptions);

    String withWhitelistedIps = Context.getWebdriversProperties("withWhitelistedIps");
    if (withWhitelistedIps != null && !"".equals(withWhitelistedIps)) {
        ChromeDriverService service = new ChromeDriverService.Builder().withWhitelistedIps(withWhitelistedIps).withVerbose(false).build();
        return new ChromeDriver(service, capabilities);
    } else {
        return new ChromeDriver(capabilities);
    }
}
 
Example 38
Project: modern.core.java.repo   File: BrowserManager.java   View source code 5 votes vote down vote up
public WebDriver maximizeBrowserAndDrivers() {
    String chromePath = System.getProperty("user.dir") + "/Drivers/chrome/chromedriver";
    System.setProperty("webdriver.chrome.driver", chromePath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--incognito");
    this.driver = new ChromeDriver();
    driver.manage().window().maximize();
    return driver;

}
 
Example 39
Project: PiYouTube   File: PiYouTube.java   View source code 5 votes vote down vote up
public void launchChromeDriver()
{
	System.setProperty("webdriver.chrome.driver", this.config.getString("driver"));
	
	ChromeOptions chromeParams = new ChromeOptions();
	
	JSONArray options = this.config.getJSONArray("chromeParams");
	if(options != null)
	{
		for(int i = 0; i < options.length(); i++)
		{
			chromeParams.addArguments(options.getString(i));
		}
	}
	
	if(this.config.optString("chrome", null) != null)
	{
		chromeParams.setBinary(this.config.getString("chrome"));
	}
	
	try
	{
		if(! Util.isUnix())
		{
			this.chromeDriver = new ChromeDriver(chromeParams);
		}
		else
		{
			this.chromeDriver = new ChromeDriver(new ChromeDriverService.Builder().withEnvironment(ImmutableMap.of("DISPLAY",":0.0")).build(), chromeParams);
		}
	}
	catch(Exception e)
	{
		System.out.println("Error loading chromedriver. Are you sure the correct path is set in config.json?");
		e.printStackTrace();
		System.exit(0);
	}
}
 
Example 40
Project: selenium-jupiter   File: ChromeDriverHandler.java   View source code 5 votes vote down vote up
@Override
public MutableCapabilities getOptions(Parameter parameter,
        Optional<Object> testInstance)
        throws IOException, IllegalAccessException {
    ChromeOptions chromeOptions = new ChromeOptions();

    // @Arguments
    Arguments arguments = parameter.getAnnotation(Arguments.class);
    if (arguments != null) {
        stream(arguments.value()).forEach(chromeOptions::addArguments);
    }

    // @Extensions
    Extensions extensions = parameter.getAnnotation(Extensions.class);
    if (extensions != null) {
        for (String extension : extensions.value()) {
            chromeOptions.addExtensions(getExtension(extension));
        }
    }

    // @Binary
    Binary binary = parameter.getAnnotation(Binary.class);
    if (binary != null) {
        chromeOptions.setBinary(binary.value());
    }

    // @Options
    Object optionsFromAnnotatedField = annotationsReader
            .getOptionsFromAnnotatedField(testInstance, Options.class);
    if (optionsFromAnnotatedField != null) {
        chromeOptions = ((ChromeOptions) optionsFromAnnotatedField)
                .merge(chromeOptions);
    }

    return chromeOptions;
}