下面列出了org.openqa.selenium.chrome.ChromeOptions#setExperimentalOption ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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.");
}
}
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);
}
public void openBrowser() throws Exception {
// loads the config options
LoadConfigProperty();
// configures the driver path
configureDriverPath();
if (config.getProperty("browserType").equals("firefox")) {
driver = new FirefoxDriver();
} else if (config.getProperty("browserType").equals("chrome")) {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.setExperimentalOption("useAutomationExtension", false);
driver = new ChromeDriver(options);
}
}
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);
}
}
private ChromeOptions buildChromeOptions() {
final ChromeOptions options = new ChromeOptions();
final Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
SYSTEM_PROPERTY_UTILS.getPropertyAsOptional(Constants.CHROME_EXECUTABLE_LOCATION_SYSTEM_PROPERTY)
.ifPresent(options::setBinary);
return options;
}
@Test
@PrepareForTest(fullyQualifiedNames = "org.vividus.selenium.WebDriverType$3")
public void testGetChromeWebDriverWithAdditionalOptions() throws Exception
{
Map<String, String> experimentalOptionValue = singletonMap(OPTION_KEY, OPTION_VALUE);
WebDriverConfiguration configuration = new WebDriverConfiguration();
configuration.setBinaryPath(Optional.of(PATH));
configuration.setCommandLineArguments(new String[] { ARGUMENT });
configuration.setExperimentalOptions(singletonMap(MOBILE_EMULATION, experimentalOptionValue));
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary(PATH);
chromeOptions.addArguments(ARGUMENT);
chromeOptions.setExperimentalOption(MOBILE_EMULATION, experimentalOptionValue);
testGetChromeWebDriver(configuration, chromeOptions);
}
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);
}
/**
* Create a Chrome WebDriver instance.
* @return The WebDriver
*/
public static EventFiringWebDriver createChrome() {
String chromeDriverBinary = WebDriverBinaryFinder.findChromeDriver();
System.setProperty("webdriver.chrome.driver", chromeDriverBinary);
log.info("Using ChromeDriver binary from {}", chromeDriverBinary);
// Prevent annoying yellow warning bar from being displayed.
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("ignore-certificate-errors"));
DesiredCapabilities caps = getCapabilities();
caps.setCapability(ChromeOptions.CAPABILITY, options);
return withReports(new ChromeDriver(caps));
}
@BeforeMethod
@Parameters({ "remoteURL", "baseURL", "OS", "browser",
"version", "internal" })
public void beforeTest(String remoteURL, String baseURL,
String OS, String browser, String version, String internal)
throws IOException {
this.testCase = new TestCase();
this.testCase.setExecutionEnvironment("{browser:"+browser+",browserVersion:"+version+",OperatingSystem:"+OS+"}");
this.testCase.setParentURL(baseURL);
this.testCase.setTestCaseId("KT"+testCaseCount++);
this.testCase.setScreenshotDirectory(log.getReportDirectory()+ File.separator + "images");
config = new WebDriverConfig();
config.setRemoteURL(remoteURL);
this.baseURL = baseURL;
config.setOS(OS);
config.setBrowserName(browser);
config.setBrowserVersion(version);
config.setIntenal(Boolean.parseBoolean(internal));
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--enable-strict-powerful-feature-restrictions");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("profile.default_content_settings.geolocation", 2);
jsonObject.addProperty("profile.default_content_setting_values.notifications",2);
options.setExperimentalOption("prefs", jsonObject);
options.addArguments("--disable-notifications");
config.setChromeOptions(options);
driver = xRemoteWebDriver.getInstance(config, log);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(this.baseURL);
}
private ChromeUser(String userName, int timeOfWaitInSeconds, ChromeOptions options) {
super(userName, timeOfWaitInSeconds);
options.setAcceptInsecureCerts(true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
options.addArguments("--disable-infobars");
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.media_stream_mic", 1);
prefs.put("profile.default_content_setting_values.media_stream_camera", 1);
options.setExperimentalOption("prefs", prefs);
String REMOTE_URL = System.getProperty("REMOTE_URL_CHROME");
if (REMOTE_URL != null) {
log.info("Using URL {} to connect to remote web driver", REMOTE_URL);
try {
this.driver = new RemoteWebDriver(new URL(REMOTE_URL), options);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
log.info("Using local web driver");
this.driver = new ChromeDriver(options);
}
this.driver.manage().timeouts().setScriptTimeout(this.timeOfWaitInSeconds, TimeUnit.SECONDS);
this.configureDriver();
}
Capabilities createCapabilities() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, createProxy());
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
if(isAndroidEnabled() || isHeadlessEnabled() || isIncognitoEnabled()) {
//Map<String, String> chromeOptions = new HashMap<String, String>();
//chromeOptions.put("androidPackage", "com.android.chrome");
ChromeOptions chromeOptions = new ChromeOptions();
if (isAndroidEnabled()) {
chromeOptions.setExperimentalOption("androidPackage", "com.android.chrome");
}
if (isHeadlessEnabled()) {
chromeOptions.addArguments("--headless");
}
if (isIncognitoEnabled()) {
chromeOptions.addArguments("--incognito");
}
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
}
if(isInsecureCertsEnabled()) {
capabilities.setCapability("acceptInsecureCerts", true);
}
return capabilities;
}
private ChromeOptions getChromeOptions() {
ChromeOptions options = new ChromeOptions();
options.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, this.alertBehaviour);
//To view pdf in chrome
options.setExperimentalOption("excludeSwitches", Arrays.asList("test-type", "--ignore-certificate-errors"));
if (this.isHeadless) {
options.addArguments("headless");
}
options.setCapability(ChromeOptions.CAPABILITY, options);
options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
options.setCapability("platform", platform);
setLoggingPrefs(options);
return options;
}
private static synchronized BrowserWebDriverContainer initializeSeleniumContainer() {
if (SELENIUMCONTAINER == null) {
java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);
final ChromeOptions theOptions = new ChromeOptions().setHeadless(true);
theOptions.addArguments("--js-flags=experimental-wasm-eh");
theOptions.addArguments("--enable-experimental-wasm-eh");
theOptions.addArguments("disable-infobars"); // disabling infobars
theOptions.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
theOptions.addArguments("--no-sandbox"); // Bypass OS security model
theOptions.setExperimentalOption("useAutomationExtension", false);
final LoggingPreferences theLoggingPreferences = new LoggingPreferences();
theLoggingPreferences.enable(LogType.BROWSER, Level.ALL);
theOptions.setCapability(CapabilityType.LOGGING_PREFS, theLoggingPreferences);
theOptions.setCapability("goog:loggingPrefs", theLoggingPreferences);
Testcontainers.exposeHostPorts(getTestWebServerPort());
SELENIUMCONTAINER = new BrowserWebDriverContainer()
.withCapabilities(theOptions)
.withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.SKIP, new File("."));
SELENIUMCONTAINER.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> SELENIUMCONTAINER.stop()));
}
return SELENIUMCONTAINER;
}
private static ChromeOptions getChromeEmulatorCaps(DesiredCapabilities caps, String deviceName) {
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", deviceName);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
chromeOptions.merge(caps);
//caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
return chromeOptions;
}
/**
* Устанавливает ChromeOptions для запуска google chrome эмулирующего работу мобильного устройства (по умолчанию nexus 5)
* Название мобильного устройства (device) может быть задано через системные переменные
*
* @return ChromeOptions
*/
private ChromeOptions getMobileChromeOptions(DesiredCapabilities capabilities) {
log.info("---------------run CustomMobileDriver---------------------");
String mobileDeviceName = loadSystemPropertyOrDefault("device", "Nexus 5");
ChromeOptions chromeOptions = new ChromeOptions().addArguments("disable-extensions",
"test-type", "no-default-browser-check", "ignore-certificate-errors");
Map<String, String> mobileEmulation = new HashMap<>();
chromeOptions.setHeadless(getHeadless());
mobileEmulation.put("deviceName", mobileDeviceName);
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
chromeOptions.merge(capabilities);
return chromeOptions;
}
/**
* setDriver method to create driver instance
*
* @param browser
* @param environment
* @param platform
* @param optPreferences
* @throws Exception
*/
@SafeVarargs
public final void setDriver(String browser,
String platform,
String environment,
Map<String, Object>... optPreferences)
throws Exception {
DesiredCapabilities caps = null;
String getPlatform = null;
props.load(new FileInputStream(Global_VARS.SE_PROPS));
switch (browser) {
case "firefox":
caps = DesiredCapabilities.firefox();
FirefoxOptions ffOpts = new FirefoxOptions();
FirefoxProfile ffProfile = new FirefoxProfile();
ffProfile.setPreference("browser.autofocus", true);
ffProfile.setPreference("browser.tabs.remote.autostart.2", false);
caps.setCapability(FirefoxDriver.PROFILE, ffProfile);
caps.setCapability("marionette", true);
// then pass them to the local WebDriver
if ( environment.equalsIgnoreCase("local") ) {
System.setProperty("webdriver.gecko.driver", props.getProperty("gecko.driver.windows.path"));
webDriver.set(new FirefoxDriver(ffOpts.merge(caps)));
}
break;
case "chrome":
caps = DesiredCapabilities.chrome();
ChromeOptions chOptions = new ChromeOptions();
Map<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("credentials_enable_service", false);
chOptions.setExperimentalOption("prefs", chromePrefs);
chOptions.addArguments("--disable-plugins", "--disable-extensions", "--disable-popup-blocking");
caps.setCapability(ChromeOptions.CAPABILITY, chOptions);
caps.setCapability("applicationCacheEnabled", false);
if ( environment.equalsIgnoreCase("local") ) {
System.setProperty("webdriver.chrome.driver", props.getProperty("chrome.driver.windows.path"));
webDriver.set(new ChromeDriver(chOptions.merge(caps)));
}
break;
case "internet explorer":
caps = DesiredCapabilities.internetExplorer();
InternetExplorerOptions ieOpts = new InternetExplorerOptions();
ieOpts.requireWindowFocus();
ieOpts.merge(caps);
caps.setCapability("requireWindowFocus", true);
if ( environment.equalsIgnoreCase("local") ) {
System.setProperty("webdriver.ie.driver", props.getProperty("ie.driver.windows.path"));
webDriver.set(new InternetExplorerDriver(ieOpts.merge(caps)));
}
break;
}
getEnv = environment;
getPlatform = platform;
sessionId.set(((RemoteWebDriver) webDriver.get()).getSessionId().toString());
sessionBrowser.set(caps.getBrowserName());
sessionVersion.set(caps.getVersion());
sessionPlatform.set(getPlatform);
System.out.println("\n*** TEST ENVIRONMENT = "
+ getSessionBrowser().toUpperCase()
+ "/" + getSessionPlatform().toUpperCase()
+ "/" + getEnv.toUpperCase()
+ "/Selenium Version=" + props.getProperty("selenium.revision")
+ "/Session ID=" + getSessionId() + "\n");
getDriver().manage().timeouts().implicitlyWait(IMPLICIT_TIMEOUT, TimeUnit.SECONDS);
getDriver().manage().window().maximize();
}
@Test
public void shouldOpenChrome() throws MalformedURLException {
/** Here we set environment variables from your local machine, or IntelliJ run configuration,
* and store these values in the variables below. Doing this is a best practice in terms of test execution
* and security. If you're not sure how to use env variables, refer to this guide -
* https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
* or check junit5-README.md */
String sauceUserName = System.getenv("SAUCE_USERNAME");
String sauceAccessKey = System.getenv("SAUCE_ACCESS_KEY");
String sauceURL = "https://ondemand.saucelabs.com/wd/hub";
/**
* * Here we set the MutableCapabilities for "sauce:options", which is required for newer versions of Selenium
* and the w3c protocol, for more info read the documentation:
* https://wiki.saucelabs.com/display/DOCS/Selenium+W3C+Capabilities+Support+-+Beta */
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("username", sauceUserName);
sauceOpts.setCapability("accessKey", sauceAccessKey);
/** In order to use w3c you must set the seleniumVersion **/
sauceOpts.setCapability("seleniumVersion", "3.141.59");
sauceOpts.setCapability("name", "4-best-practices");
/**
* in this exercise we set additional capabilities below that align with
* testing best practices such as tags, timeouts, and build name/numbers.
*
* Tags are an excellent way to control and filter your test automation
* in Sauce Analytics. Get a better view into your test automation.
*/
List<String> tags = Arrays.asList("sauceDemo", "demoTest", "module4", "javaTest");
sauceOpts.setCapability("tags", tags);
/** Another of the most important things that you can do to get started
* is to set timeout capabilities for Sauce based on your organizations needs. For example:
* How long is the whole test allowed to run?*/
sauceOpts.setCapability("maxDuration", 3600);
/** A Selenium crash might cause a session to hang indefinitely.
* Below is the max time allowed to wait for a Selenium command*/
sauceOpts.setCapability("commandTimeout", 600);
/** How long can the browser wait for a new command */
sauceOpts.setCapability("idleTimeout", 1000);
/** Setting a build name is one of the most fundamental pieces of running
* successful test automation. Builds will gather all of your tests into a single
* 'test suite' that you can analyze for results.
* It's a best practice to always group your tests into builds. */
sauceOpts.setCapability("build", "Onboarding Sample App - Java-Junit5");
/** Required to set w3c protoccol **/
ChromeOptions chromeOpts = new ChromeOptions();
chromeOpts.setExperimentalOption("w3c", true);
/** Set a second MutableCapabilities object to pass Sauce Options and Chrome Options **/
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("sauce:options", sauceOpts);
capabilities.setCapability("goog:chromeOptions", chromeOpts);
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("platformVersion", "Windows 10");
capabilities.setCapability("browserVersion", "latest");
/** If you're accessing the EU data center, use the following endpoint:.
* https://ondemand.eu-central-1.saucelabs.com/wd/hub
* */
driver = new RemoteWebDriver(new URL(sauceURL), capabilities);
/** Don't forget to enter in your application's URL in place of 'https://www.saucedemo.com'. */
driver.navigate().to("https://www.saucedemo.com");
assertTrue(true);
}
/**
* @BeforeEach is a JUnit 5 annotation that defines specific prerequisite test method behaviors.
In the example below we:
- Define Environment Variables for Sauce Credentials ("SAUCE_USERNAME" and "SAUCE_ACCESS_KEY")
- Define Chrome Options such as W3C protocol
- Define the "sauce:options" capabilities, indicated by the "sauceOpts" MutableCapability object
- Define the WebDriver capabilities, indicated by the "caps" DesiredCapabilities object
- Define the service URL for communicating with SauceLabs.com indicated by "sauceURL" string
- Set the URL to sauceURl
- Set the driver instance to a RemoteWebDriver
- Pass "url" and "caps" as parameters of the RemoteWebDriver
For more information visit the docs: https://junit.org/junit5/docs/5.0.2/api/org/junit/jupiter/api/BeforeEach.html
*/
@BeforeEach
public void setup(TestInfo testInfo) throws MalformedURLException {
String username = System.getenv("SAUCE_USERNAME");
String accessKey = System.getenv("SAUCE_ACCESS_KEY");
String methodName = testInfo.getDisplayName();
/** ChomeOptions allows us to set browser-specific behavior such as profile settings, headless capabilities, insecure tls certs,
and in this example--the W3C protocol
For more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeOptions.html */
ChromeOptions chromeOpts = new ChromeOptions();
chromeOpts.setExperimentalOption("w3c", true);
/** The MutableCapabilities class came into existence with Selenium 3.6.0 and acts as the parent class for
all browser implementations--including the ChromeOptions class extension.
Fore more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/MutableCapabilities.html */
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("name", methodName);
sauceOpts.setCapability("build", "Java-W3C-Examples");
sauceOpts.setCapability("seleniumVersion", "3.141.59");
sauceOpts.setCapability("username", username);
sauceOpts.setCapability("accessKey", accessKey);
sauceOpts.setCapability("tags", testInfo.getTags());
/** Below we see the use of our other capability objects, 'chromeOpts' and 'sauceOpts',
defined in ChromeOptions.CAPABILITY and sauce:options respectively.
*/
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");
/** Finally, we pass our DesiredCapabilities object 'caps' as a parameter of our RemoteWebDriver instance */
String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
URL url = new URL(sauceUrl);
driver = new RemoteWebDriver(url, caps);
}
/**
* List of Chromium Command Line Switches
* http://peter.sh/experiments/chromium-command-line-switches/#disable-popup-blocking
*/
private void setupChrome() {
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("profile.default_content_setting_values.notifications", 2);
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", DOWNLOAD_DIRECTORY);
prefs.put("download.prompt_for_download", false);
prefs.put("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1);
prefs.put("safebrowsing.enabled", true);
prefs.put("plugins.always_open_pdf_externally", true);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("useAutomationExtension", false);
chromeOptions.setExperimentalOption("prefs", prefs);
chromeOptions.addArguments("allow-file-access");
chromeOptions.addArguments("allow-file-access-from-files");
chromeOptions.addArguments("disable-background-networking");
chromeOptions.addArguments("disable-background-timer-throttling");
chromeOptions.addArguments("disable-breakpad");
chromeOptions.addArguments("disable-child-account-detection");
chromeOptions.addArguments("disable-clear-browsing-data-counters");
chromeOptions.addArguments("disable-client-side-phishing-detection");
chromeOptions.addArguments("disable-cloud-import");
chromeOptions.addArguments("disable-component-cloud-policy");
chromeOptions.addArguments("disable-component-update");
chromeOptions.addArguments("disable-default-apps");
chromeOptions.addArguments("disable-download-notification");
chromeOptions.addArguments("disable-extensions");
chromeOptions.addArguments("disable-extensions-file-access-check");
chromeOptions.addArguments("disable-extensions-http-throttling");
chromeOptions.addArguments("disable-hang-monitor");
chromeOptions.addArguments("disable-infobars");
chromeOptions.addArguments("disable-popup-blocking");
chromeOptions.addArguments("disable-print-preview");
chromeOptions.addArguments("disable-prompt-on-repost");
chromeOptions.addArguments("disable-sync");
chromeOptions.addArguments("disable-translate");
chromeOptions.addArguments("disable-web-resources");
chromeOptions.addArguments("disable-web-security");
chromeOptions.addArguments("dns-prefetch-disable");
chromeOptions.addArguments("download-whole-document");
chromeOptions.addArguments("enable-logging");
chromeOptions.addArguments("enable-screenshot-testing-with-mode");
chromeOptions.addArguments("ignore-certificate-errors");
chromeOptions.addArguments("log-level=0");
chromeOptions.addArguments("metrics-recording-only");
chromeOptions.addArguments("mute-audio");
chromeOptions.addArguments("no-default-browser-check");
chromeOptions.addArguments("no-displaying-insecure-content");
chromeOptions.addArguments("no-experiments");
chromeOptions.addArguments("no-first-run");
chromeOptions.addArguments("no-sandbox");
chromeOptions.addArguments("no-service-autorun");
chromeOptions.addArguments("noerrdialogs");
chromeOptions.addArguments("password-store=basic");
chromeOptions.addArguments("reduce-security-for-testing");
chromeOptions.addArguments("safebrowsing-disable-auto-update");
chromeOptions.addArguments("safebrowsing-disable-download-protection");
chromeOptions.addArguments("safebrowsing-disable-extension-blacklist");
chromeOptions.addArguments("start-maximized");
chromeOptions.addArguments("test-type=webdriver");
chromeOptions.addArguments("use-mock-keychain");
chromeOptions.setHeadless(BROWSER_HEADLESS);
capabilities.merge(chromeOptions);
}
/**
* Generates a chrome webdriver.
*
* @return
* A chrome webdriver
* @throws TechnicalException
* if an error occured when Webdriver setExecutable to true.
*/
private WebDriver generateGoogleChromeDriver() 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));
}
log.info("Generating Chrome driver ({}) ...", pathWebdriver);
System.setProperty(Driver.CHROME.getDriverName(), pathWebdriver);
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
chromeOptions.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
chromeOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
chromeOptions.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
setLoggingLevel(chromeOptions);
chromeOptions.addArguments("--ignore-certificate-errors");
if (Context.isHeadless()) {
chromeOptions.addArguments("--headless");
}
// Proxy configuration
if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) {
chromeOptions.setCapability(CapabilityType.PROXY, Context.getProxy());
}
// add Modifyheader Extensions to Chrome
if (Context.getWebdriversProperties(MODIFYHEADER_PATH) != null && !"".equals(Context.getWebdriversProperties(MODIFYHEADER_PATH))) {
chromeOptions.addExtensions(new File(Context.getWebdriversProperties(MODIFYHEADER_PATH)));
}
// Set custom downloaded file path. When you check content of downloaded file by robot.
final HashMap<String, Object> chromePrefs = new HashMap<>();
chromePrefs.put("download.default_directory", System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER);
chromeOptions.setExperimentalOption("prefs", chromePrefs);
// Set custom chromium (if you not use default chromium on your target device)
final String targetBrowserBinaryPath = Context.getWebdriversProperties(TARGET_BROWSER_BINARY_PATH);
if (targetBrowserBinaryPath != null && !"".equals(targetBrowserBinaryPath)) {
chromeOptions.setBinary(targetBrowserBinaryPath);
}
log.info("addArguments [{}] to webdriver.", Context.getWebdriversProperties(WEBDRIVER_OPTIONS_ADDITIONAL_ARGS));
for (String additionalArgument : Context.getWebdriversProperties(WEBDRIVER_OPTIONS_ADDITIONAL_ARGS).split(",")) {
log.info("addArgument [{}] to webdriver.", additionalArgument);
chromeOptions.addArguments(additionalArgument);
}
if (Context.getWebdriversProperties(REMOTE_WEBDRIVER_URL) != null && !"".equals(Context.getWebdriversProperties(REMOTE_WEBDRIVER_URL))
&& Context.getWebdriversProperties(REMOTE_WEBDRIVER_BROWSER_VERSION) != null && !"".equals(Context.getWebdriversProperties(REMOTE_WEBDRIVER_BROWSER_VERSION))
&& Context.getWebdriversProperties(REMOTE_WEBDRIVER_PLATFORM_NAME) != null && !"".equals(Context.getWebdriversProperties(REMOTE_WEBDRIVER_PLATFORM_NAME))) {
chromeOptions.setCapability("browserVersion", Context.getWebdriversProperties(REMOTE_WEBDRIVER_BROWSER_VERSION));
chromeOptions.setCapability("platformName", Context.getWebdriversProperties(REMOTE_WEBDRIVER_PLATFORM_NAME));
try {
return new RemoteWebDriver(new URL(Context.getWebdriversProperties(REMOTE_WEBDRIVER_URL)), chromeOptions);
} catch (MalformedURLException e) {
throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_REMOTE_WEBDRIVER_URL));
}
} else {
final String withWhitelistedIps = Context.getWebdriversProperties(WITH_WHITE_LISTED_IPS);
if (withWhitelistedIps != null && !"".equals(withWhitelistedIps)) {
final ChromeDriverService service = new ChromeDriverService.Builder().withWhitelistedIps(withWhitelistedIps).withVerbose(false).build();
return new ChromeDriver(service, chromeOptions);
} else {
return new ChromeDriver(chromeOptions);
}
}
}