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

The following examples show how to use org.openqa.selenium.chrome.ChromeOptions. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: vividus   Source File: WebDriverFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public WebDriver getRemoteWebDriver(DesiredCapabilities desiredCapabilities)
{
    DesiredCapabilities mergedDesiredCapabilities = getWebDriverCapabilities(false, desiredCapabilities);
    WebDriverType webDriverType = WebDriverManager.detectType(mergedDesiredCapabilities);

    Capabilities capabilities = mergedDesiredCapabilities;
    if (webDriverType != null)
    {
        webDriverType.prepareCapabilities(mergedDesiredCapabilities);
        if (webDriverType == WebDriverType.CHROME)
        {
            WebDriverConfiguration configuration = getWebDriverConfiguration(webDriverType, false);
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments(configuration.getCommandLineArguments());
            configuration.getExperimentalOptions().forEach(chromeOptions::setExperimentalOption);
            capabilities = chromeOptions.merge(mergedDesiredCapabilities);
        }
    }
    return createWebDriver(remoteWebDriverFactory.getRemoteWebDriver(remoteDriverUrl, capabilities));
}
 
Example 2
@Test
public void recordingTestThatShouldBeRecordedButNotPersisted() {
    try (
        // withRecordingFileFactory {
        BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
            // }
            .withCapabilities(new ChromeOptions())
            // withRecordingFileFactory {
            .withRecordingFileFactory(new CustomRecordingFileFactory())
        // }
    ) {
        chrome.start();

        doSimpleExplore(chrome);
    }
}
 
Example 3
Source Project: JYTB   Source File: BotWorker.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void setChromeDriver() {
        ChromeOptions options = new ChromeOptions();
        List<String> chromeOptions = new ArrayList<>();
        LoggingPreferences logPrefs = new LoggingPreferences();

        chromeOptions.add(String.format("--proxy-server=%s", proxies.getCurrentProxyModel().getIp()));
        chromeOptions.add(String.format("--user-agent=%s", userAgent.randomUA()));
        chromeOptions.add("--mute-audio");

        logPrefs.enable(LogType.BROWSER, Level.ALL);
        logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
        options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        options.addArguments(chromeOptions);
        options.setBinary(this.driverLocation);
        options.setHeadless(true);
//        options.setProxy(this.proxies.getCurrentProxy());
        options.setCapability("proxy", this.proxies.getCurrentProxy());

        this.webDriver = new ChromeDriver(options);
        Log.WINFO(this.workerName, this.workerColor, "Chrome Driver Set.");
    }
 
Example 4
/**
 * Start the Selenium chrome driver instance with lean options
 */
public void startDriver(){
    if (serviceManager != null){
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");
        HashMap<String, Object> prefs = new HashMap<String, Object>(); 
        prefs.put("profile.managed_default_content_settings.images", 2);
        options.setExperimentalOption("prefs", prefs); 

        driver = new RemoteWebDriver(serviceManager.getService().getUrl(), options);
        driver.manage().timeouts().implicitlyWait(PAGE_WAIT_TIMEOUT, TimeUnit.SECONDS); // Wait for the page to be completely loaded. Or reasonably loaded.
    }
    else {
        System.err.println("[JS-SRI][-] You must set a driver service manager before you can start a driver.");
    }
}
 
Example 5
@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 6
Source Project: AndroidRobot   Source File: ChromeDriverClient.java    License: Apache License 2.0 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 7
@BeforeMethod
public void setup() {

    System.setProperty("webdriver.chrome.driver",
            "./src/test/resources/drivers/chromedriver");

    Map<String, Object> deviceMetrics = new HashMap<>();
    deviceMetrics.put("width", 411);
    deviceMetrics.put("height", 823);
    deviceMetrics.put("pixelRatio", 3.0);


    Map<String, Object> mobileEmulation = new HashMap<>();
    mobileEmulation.put("deviceMetrics", deviceMetrics);
    mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 8.0.0;" +
            "Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) " +
            "Chrome/67.0.3396.99 Mobile Safari/537.36");

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);

    driver = new ChromeDriver(chromeOptions);
    driver.get("http://demo-store.seleniumacademy.com/");

}
 
Example 8
Source Project: agent   Source File: ChromeDevice.java    License: MIT License 6 votes vote down vote up
@Override
protected Capabilities newCaps(Capabilities capsToMerge) {
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--ignore-certificate-errors");
    chromeOptions.addArguments("no-default-browser-check");

    // **** 以上capabilities可被传入的caps覆盖 ****

    chromeOptions.merge(capsToMerge);

    // **** 以下capabilities具有更高优先级,将覆盖传入的caps ****

    if (!StringUtils.isEmpty(browser.getPath())) {
        chromeOptions.setBinary(browser.getPath());
    }

    return chromeOptions;
}
 
Example 9
Source Project: qa-automation-samples   Source File: DriverFactory.java    License: MIT License 6 votes vote down vote up
public static WebDriver createDriver(String mvnParameter){
    if (mvnParameter == null){
        System.setProperty(Browsers.CHROME_MAC.getBrowserType(),
        		OperationSystems.MAC_OS_X.getDriversPath().concat(Browsers.CHROME_MAC.getExecutable()));
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-fullscreen", "--disable-gpu");
        return new ChromeDriver(options);
    }

    try {
        String soName = getSoName();
        String browserType = getBrowserTypeFromParameter(mvnParameter);
        System.setProperty(browserType, getDriversPath(soName).concat(getFullExecutableNameFromParameter(mvnParameter)));
    }catch (Exception e){
        System.out.println("ERROR: Please select one of the valid browsers for the test.");
        Browsers.showAvaliableBrowsersOptions();
        System.exit(1);
    }
		
    return Browsers.valueOf(mvnParameter).createDriverInstance();
}
 
Example 10
Source Project: demo-java   Source File: UpdateSauceStatusTest.java    License: MIT License 6 votes vote down vote up
public void setUp() throws MalformedURLException {
    String username = System.getenv("SAUCE_USERNAME");
    String accessKey = System.getenv("SAUCE_ACCESS_KEY");

    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("username", username);
    sauceOpts.setCapability("accessKey", accessKey);

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(ChromeOptions.CAPABILITY,  chromeOpts);
    caps.setCapability("sauce:options", sauceOpts);
    caps.setCapability("browserName", "googlechrome");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "windows 10");

    String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
    URL url = new URL(sauceUrl);
    driver = new RemoteWebDriver(url, caps);
}
 
Example 11
Source Project: JTAF-ExtWebDriver   Source File: DefaultSessionFactory.java    License: Apache License 2.0 6 votes vote down vote up
private ChromeOptions setChromeOptions(ClientProperties properties){
	HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
               
	// for downloading with Chrome
	if(properties.getDownloadFolder() != null) {
		chromePrefs.put("profile.default_content_settings.popups", 0);
		chromePrefs.put("download.default_directory", properties.getDownloadFolder());
	}
	
	if(properties.shouldEnableFlash()) {  
		chromePrefs.put("profile.default_content_setting_values.plugins",1);  
		chromePrefs.put("profile.content_settings.plugin_whitelist.adobe-flash-player",1);  
		chromePrefs.put("profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player",1);  
	}

	ChromeOptions chromeOptions = new ChromeOptions();
	chromeOptions.setExperimentalOption("prefs", chromePrefs);
	
	return chromeOptions;
}
 
Example 12
Source Project: webtau   Source File: WebDriverCreator.java    License: Apache License 2.0 6 votes vote down vote up
private static ChromeDriver createChromeDriver() {
    ChromeOptions options = new ChromeOptions();

    if (BrowserConfig.getChromeBinPath() != null) {
        options.setBinary(BrowserConfig.getChromeBinPath().toFile());
    }

    if (BrowserConfig.getChromeDriverPath() != null) {
        System.setProperty(CHROME_DRIVER_PATH_KEY, BrowserConfig.getChromeDriverPath().toString());
    }

    if (BrowserConfig.isHeadless()) {
        options.addArguments("--headless");
        options.addArguments("--disable-gpu");
    }

    if (System.getProperty(CHROME_DRIVER_PATH_KEY) == null) {
        setupDriverManagerConfig();
        downloadDriverMessage("chrome");
        WebDriverManager.chromedriver().setup();
    }

    return new ChromeDriver(options);
}
 
Example 13
public static DesiredCapabilities build(RemoteCapability capability){
 DesiredCapabilities desiredCapabilities;
 if(RemoteCapability.CHROME.equals(capability)){
  ChromeOptions options = new ChromeOptions();
     desiredCapabilities = DesiredCapabilities.chrome();
     desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
  return desiredCapabilities;
 } else if (RemoteCapability.FIREFOX.equals(capability)){
  FirefoxProfile profile = new FirefoxProfile();
  desiredCapabilities = DesiredCapabilities.firefox();
  desiredCapabilities.setCapability(FirefoxDriver.PROFILE, profile);
  return desiredCapabilities;
 } else if (RemoteCapability.INTERNET_EXPLORER.equals(capability)){
  desiredCapabilities = DesiredCapabilities.internetExplorer();
  return desiredCapabilities;
 } else if (RemoteCapability.PHANTOMJS.equals(capability)){
  desiredCapabilities = DesiredCapabilities.phantomjs();
  return desiredCapabilities;
 }
 throw new IllegalArgumentException("No such capability");
}
 
Example 14
Source Project: webdrivermanager-examples   Source File: StabilityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(NUM_THREADS);
    ExecutorService executorService = newFixedThreadPool(NUM_THREADS);

    for (int i = 0; i < NUM_THREADS; i++) {
        executorService.submit(() -> {
            try {
                WebDriverManager.chromedriver().setup();
                ChromeOptions options = new ChromeOptions();
                options.addArguments("--headless");
                WebDriver driver = new ChromeDriver(options);
                driver.get(
                        "https://bonigarcia.github.io/selenium-jupiter/");
                String title = driver.getTitle();
                System.out.println(title);
                driver.quit();
            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();
    executorService.shutdown();
}
 
Example 15
@Test
public void honorPresetNoProxyEnvironment() {
    try (
        BrowserWebDriverContainer chromeWithNoProxySet = (BrowserWebDriverContainer) new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions())
            .withEnv(NO_PROXY_KEY, NO_PROXY_VALUE)
    ) {
        chromeWithNoProxySet.start();

        Object noProxy = chromeWithNoProxySet.getEnvMap().get(NO_PROXY_KEY);
        assertEquals("no_proxy should be preserved by the container rule", NO_PROXY_VALUE, noProxy);
    }
}
 
Example 16
@Test
public void recordingTestThatShouldBeRecordedAndRetained() {
    File target = vncRecordingDirectory.getRoot();
    try (
        // recordFailing {
        // or if you only want videos for test failures:
        BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions())
            .withRecordingMode(RECORD_FAILING, target)
            // }
            .withRecordingFileFactory(new DefaultRecordingFileFactory())
    ) {
        chrome.start();

        doSimpleExplore(chrome);
        chrome.afterTest(new TestDescription() {
            @Override
            public String getTestId() {
                return getFilesystemFriendlyName();
            }

            @Override
            public String getFilesystemFriendlyName() {
                return "ChromeThatRecordsFailingTests-recordingTestThatShouldBeRecordedAndRetained";
            }
        }, Optional.of(new RuntimeException("Force writing of video file.")));

        String[] files = vncRecordingDirectory.getRoot().list(new PatternFilenameFilter("FAILED-.*\\.flv"));
        assertEquals("Recorded file not found", 1, files.length);
    }

}
 
Example 17
Source Project: vividus   Source File: WebDriverFactoryTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetRemoteWebDriverIsChromeWithAdditionalOptions() throws Exception
{
    String args = "disable-blink-features=BlockCredentialedSubresources";
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments(args);
    chromeOptions.setExperimentalOption("w3c", Boolean.TRUE);
    lenient().doReturn(args).when(propertyParser).getPropertyValue(
            String.format(COMMAND_LINE_ARGUMENTS_PROPERTY_FORMAT, WebDriverType.CHROME));
    lenient().doReturn("{\"w3c\":true}").when(propertyParser).getPropertyValue(
            String.format(EXPERIMENTAL_OPTIONS_PROPERTY_FORMAT, WebDriverType.CHROME));
    testGetRemoteWebDriverIsChrome(chromeOptions);
}
 
Example 18
Source Project: vividus   Source File: WebDriverTypeTests.java    License: Apache License 2.0 5 votes vote down vote up
private static void testGetChromeWebDriver(WebDriverConfiguration configuration, ChromeOptions chromeOptions)
        throws Exception
{
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
    ChromeDriver expected = mock(ChromeDriver.class);
    whenNew(ChromeDriver.class).withParameterTypes(ChromeOptions.class).withArguments(chromeOptions)
            .thenReturn(expected);
    WebDriver actual = WebDriverType.CHROME.getWebDriver(desiredCapabilities, configuration);
    assertEquals(expected, actual);
}
 
Example 19
Source Project: aquality-selenium-java   Source File: ChromeSettings.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChromeOptions getCapabilities() {
    ChromeOptions chromeOptions = new ChromeOptions();
    setChromePrefs(chromeOptions);
    setCapabilities(chromeOptions);
    setChromeArgs(chromeOptions);
    chromeOptions.setPageLoadStrategy(getPageLoadStrategy());
    return chromeOptions;
}
 
Example 20
Source Project: aquality-selenium-java   Source File: ChromeSettings.java    License: Apache License 2.0 5 votes vote down vote up
private void setChromePrefs(ChromeOptions options){
    HashMap<String, Object> chromePrefs = new HashMap<>();
    Map<String, Object> configOptions = getBrowserOptions();
    configOptions.forEach((key, value) -> {
        if (key.equals(getDownloadDirCapabilityKey())) {
            chromePrefs.put(key, getDownloadDir());
        } else {
            chromePrefs.put(key, value);
        }
    });
    options.setExperimentalOption("prefs", chromePrefs);
}
 
Example 21
Source Project: frameworkium-core   Source File: ElectronImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChromeOptions getCapabilities() {
    if (!APP_PATH.isSpecified()) {
        throw new IllegalStateException(
                "App path must be specified when using Electron!");
    }

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setBinary(APP_PATH.getValue());
    return chromeOptions;
}
 
Example 22
Source Project: frameworkium-core   Source File: ChromeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChromeOptions getCapabilities() {
    ChromeOptions chromeOptions = new ChromeOptions();

    // useful defaults
    chromeOptions.setCapability(
            "chrome.switches",
            Collections.singletonList("--no-default-browser-check"));
    chromeOptions.setCapability(
            "chrome.prefs",
            ImmutableMap.of("profile.password_manager_enabled", "false"));

    // Workaround Docker/Travis issue
    if (Boolean.parseBoolean(System.getenv("CHROME_NO_SANDBOX"))) {
        chromeOptions.addArguments("--no-sandbox");
    }

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

    chromeOptions.setHeadless(Property.HEADLESS.getBoolean());
    return chromeOptions;
}
 
Example 23
Source Project: openvidu   Source File: ChromeUser.java    License: Apache License 2.0 5 votes vote down vote up
private static ChromeOptions generateCustomScreenChromeOptions(String screenToCapture, boolean runningAsRoot,
		Path audioFileLocation) {
	ChromeOptions options = new ChromeOptions();
	// This flag selects the entire screen as video source when screen sharing
	options.addArguments("--auto-select-desktop-capture-source=" + screenToCapture);
	options.addArguments("--use-fake-device-for-media-stream");
	options.addArguments("--use-file-for-fake-audio-capture=" + audioFileLocation.toString());

	if (runningAsRoot) {
		options.addArguments("--no-sandbox");
	}

	return options;
}
 
Example 24
Source Project: healenium-web   Source File: HealTurnedOffTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void createDriver() {
    ChromeOptions options = new ChromeOptions();
    options.setHeadless(true);
    WebDriver delegate = new ChromeDriver(options);
    Config config = ConfigFactory.load("test.conf");
    SelfHealingEngine engine = new SelfHealingEngine(delegate, config);
    driver = SelfHealingDriver.create(engine);
}
 
Example 25
Source Project: coteafs-selenium   Source File: Browser.java    License: Apache License 2.0 5 votes vote down vote up
private static WebDriver setupChromeDriver() throws MalformedURLException {
    LOG.i("Setting up Chrome driver...");
    System.setProperty("webdriver.chrome.silentOutput", "true");
    setupDriver(chromedriver());
    final ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--dns-prefetch-disable");
    if (appSetting().isHeadlessMode()) {
        chromeOptions.addArguments("--headless");
    }
    chromeOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    final ChromeDriverService chromeService = ChromeDriverService.createDefaultService();
    return new ChromeDriver(chromeService, chromeOptions);
}
 
Example 26
@BeforeMethod
public void setup() {

    System.setProperty("webdriver.chrome.driver",
            "./src/test/resources/drivers/chromedriver");
    ChromeOptions  chromeOptions = new ChromeOptions();
    chromeOptions.setHeadless(true);
    driver = new ChromeDriver(chromeOptions);
    driver.get("http://demo-store.seleniumacademy.com/");

}
 
Example 27
@Before
public void setupTest() {
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setHeadless(true);
    driver = new ChromeDriver(chromeOptions);
    wait = new WebDriverWait(driver, Duration.ofSeconds(5));
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
 
Example 28
Source Project: selenium   Source File: InternalSelenseTestBase.java    License: Apache License 2.0 5 votes vote down vote up
private Capabilities createCapabilities() {
  String property = System.getProperty("selenium.browser", "ff");

  Browser browser = Browser.detect();
  switch (browser) {
    case CHROME:
      return new ChromeOptions();

    case EDGE:
      return new EdgeHtmlOptions();

    case CHROMIUMEDGE:
      return new EdgeOptions();

    case IE:
      return new InternetExplorerOptions();

    case FIREFOX:
    case MARIONETTE:
      return new FirefoxOptions();

    case OPERA:
    case OPERABLINK:
      return new OperaOptions();

    case SAFARI:
      return new SafariOptions();

    default:
      fail("Attempt to use an unsupported browser: " + property);
      // we never get here, but keep null checks happy anyway
      return new DesiredCapabilities();
  }
}
 
Example 29
@Before
public void setupTest() {
    ChromeOptions options = new ChromeOptions();

    // This flag avoids to grant the user media
    options.addArguments("--use-fake-ui-for-media-stream");

    // This flag fakes user media with synthetic video (green with spinner
    // and timer)
    options.addArguments("--use-fake-device-for-media-stream");

    driver = new ChromeDriver(options);
}
 
Example 30
Source Project: site-infrastructure-tests   Source File: PageSteps.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void beforeTest() {
	logger.info("Test setup...");
	ChromeOptions chromeOptions = new ChromeOptions();
	chromeOptions.addArguments("--headless");
	// driver = new ChromeDriver(chromeOptions);
	if (logger.isDebugEnabled()) {
		logger.debug("Initialising ChromeDriver...");
	}
	driver = new RemoteWebDriver(CucumberFeatureTest.getService().getUrl(), chromeOptions);
	_jsExecutor = (JavascriptExecutor) driver;
	logger.info("Test setup complete.");
}