Chromeoptions and setExperimentalOption code - java

I am unable to understand the meaning of following lines of code for setting up Chromeoptions in selenium code
Can someone explain its meaning and als provide some external link for further learning -:
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
prefs.put("profile.default_content_setting_values.notifications", 2);
options.setExperimentalOption("prefs", prefs);
Any help on this issue will be highly appreciated.

Here is the complete details :
ChromeOptions options = new ChromeOptions();
Through this line you are creating an object by the name options of ChromeOptions Class.
Map<String, Object> prefs = new HashMap<String, Object>();
Here you have created a new Map object by the name prefs where the Key and Value fields accepts String and Object type of data and casted it to HashMap.
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
prefs.put("profile.default_content_setting_values.notifications", 2);
In these three lines you have configured the pref-names within the prefs object.
options.setExperimentalOption("prefs", prefs);
Finally in this line you are using the setExperimentalOption method to set these experimental options (ChromeDriver options not yet exposed through the ChromeOptions API) within the options object.
Now you can use this options object of ChromeOptions Class to initialize the WebDriver and Web Client as follows :
WebDriver driver = new ChromeDriver(options);

These are chrome browser preferences. You can set using options. You can find full list here in source code of chromium
https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup

Related

How dismiss ALERT popup while opening a browser

I open a browser:
'''
https://portal-qa1.maytronics.co/#/login/login
After successfully logging in (user: Shoval.Ziman#comm-it.com, pass: 123456),
I go to the page I need and a ALERT message appears.
I tried to remove it in many ways, nothing comes out.
The switchTo() method - doesn't work.
The Robot(), doesn't work two:
Robot alertAllow = new Robot();
alertAllow.mouseMove(280, 160);
alertAllow.mousePress(InputEvent.BUTTON1_DOWN_MASK);
alertAllow.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(3000);
Also I tried to use the next method:
WebDriverManager.chromedriver().setup();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
and that didn't help either.
Try this:
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_ENTER);
// or
robot.keyPress(KeyEvent.VK_ESCAPE);
Usually, after hitting enter or escape most alerts go away.

How Can I get network files in google chrome with selenium?

I am using selenium for a test in a project, but I have a problem.
I need to get network files from google chrome when I inspect element.
In this section I need this files, they are JSON files, and I need its information.
//String scriptToExecute = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;";
String scriptToExecute = "var network = performance.getEntries() || {}; return network;";
java.util.List<String> s= executeJavaScript(scriptToExecute)
String s attribute, return me a strange List of strange objects of the network, isn't good information for me.
This is my problem, I need JSON files, but my code returns me other things.
Use BrowserMobProxyServer along with selenium to get the network details of each network HAR format.
// Set up BrowserMobProxyServer while initiation driver
proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
driver = new ChromeDriver(capabilities);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("google.com");
// Do all your navigation in selenium/ selenide code
driver.get("http://google.com");
// After navigation, you can find network details stored HAR
Har har = proxy.getHar();
If required you can store it to file before quiting the driver,
Har har = proxy.getHar();
File harFile = new File(sFileName);
har.writeTo(harFile);
proxy.stop();
driver.quit();
1.Create a webdriver with capabilities to monitor network calls too.
public static WebDriver getDriver() {
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.driver", Driver local path);
DesiredCapabilities cap = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
Map<String, Object> perfLogPrefs = new HashMap<String, Object>();
perfLogPrefs.put("traceCategories", "browser,devtools.timeline,devtools"); // comma-separated trace categories
options.setExperimentalOption("perfLoggingPrefs", perfLogPrefs);
cap.setCapability(ChromeOptions.CAPABILITY, options);
return new ChromeDriver(cap);
}
Now retrieve your log entries using following code.
for (LogEntry entry : driver.manage().logs().get(LogType.PERFORMANCE)){
System.out.println(entry.toString());
}
3.Result will be in following JSON format.
{
"webview": <originating WebView ID>,
"message": { "method": "...", "params": { ... }} // DevTools message.
}
You can use return JSON.stringify(network) replace return network.Then executeJavaScript(scriptToExecute) will return json,but it still String If you don't change to json by java.You can use org.json.Just
JSONArray netData = new JSONArray(driver.executeScript(scriptToExecute).toString());

Download files in Java, Selenium using ChromeDriver and headless mode

As it is still not clear for me how to download files using --headless mode in ChromeDriver - selenium [Java], add here please the example of how to do so, I try to do it like that (the file downloading works properly without --headless option):
ChromeOptions lChromeOptions = new ChromeOptions();
HashMap<String, Object> lChromePrefs = new HashMap<String, Object>();
lChromePrefs.put("profile.default_content_settings.popups", 0);
lChromePrefs.put("download.default_directory", _PATH_TO_DOWNLOAD_DIR);
lChromePrefs.put("browser.set_download_behavior", "{ behavior: 'allow' , downloadPath: '"+_PATH_TO_DOWNLOAD_DIR+"'}");
lChromeOptions.addArguments("--headless");
lChromeOptions.addArguments("--disable-gpu");
lChromeOptions.setExperimentalOption("prefs", lChromePrefs);
WebDriver lWebDriver = new ChromeDriver(lChromeOptions);
From what I know, downloading files in headless mode should be possible since Chrome v60+ by setting Browser.setDownloadBehaviour(true, _DIRECTORY) but I cant find the information whether ChromeDriver already supports it or it is just me using wrong chrome preferences as arguments
ChromeDriver version: 2.34
Selenium + WebDriver version: 3.8.1
In Java use like this :
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup
ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver driver = new ChromeDriver(driverService, options);
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", "//home//vaibhav//Desktop");
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
httpClient.execute(request);
driver.get("http://www.seleniumhq.org/download/");
driver.findElement(By.linkText("32 bit Windows IE")).click();
As per official release page of chrome driver, a fix has been introduced for this issue. Any chrome driver version greater than 77 will be able to download the file in headless mode.
options.addArguments("--headless");

org.openqa.selenium.InvalidArgumentException: Invalid capabilities using DesiredCapabilities

I have upgraded my Selenium framework to the latest version. During execution of the code, I receive the following exception:
Exception:
org.openqa.selenium.InvalidArgumentException:
Invalid capabilities in alwaysMatch: unhandledPromptBehavior is type boolean instead of string
Details:
Selenium: 3.7.1;
IE: 3.7.0 (32 Bit Driver);
java.version: '1.8.0_144'.
Also newer version suggests driver = new InternetExplorerDriver(capabilities); is deprecated. I am setting capabilities of the browser separately in a function and passing it as a parameter in Driver.
How to resolve this issue?
Code snippet:
desiredCapabilities(browser);
IE Capabilities Setting:-
capabilities = new DesiredCapabilities().internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(CapabilityType.SUPPORTS_ALERTS, true);
capabilities.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR, true);
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
capabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
capabilities.setCapability("nativeEvents", false);
capabilities.setCapability("requireWindowFocus", false);
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("ignoreProtectedModeSettings", true);
System.setProperty("webdriver.ie.driver", ieExe.getAbsolutePath());
Then I invoke my driver:
driver = new InternetExplorerDriver(capabilities);
Well, the Selenium implementation from v3.7 on wards no more accepts DesiredCapabilities type objects as a parameter to initialize Web Browser instances rather only strongly typed Options classes are preferred. So you have to use InternetExplorerOptions Class object, use merge argument from MutableCapabilities and pass as a parameter. Your code block will be as follows :
System.setProperty("webdriver.ie.driver", "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS", true);
capabilities.setCapability("ACCEPT_SSL_CERTS", true);
capabilities.setCapability("SUPPORTS_ALERTS", true);
capabilities.setCapability("UNEXPECTED_ALERT_BEHAVIOR", true);
capabilities.setCapability("IE_ENSURE_CLEAN_SESSION", true);
capabilities.setCapability("ENABLE_ELEMENT_CACHE_CLEANUP", true);
capabilities.setCapability("nativeEvents", false);
capabilities.setCapability("requireWindowFocus", false);
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("ignoreProtectedModeSettings", true);
InternetExplorerOptions opt = new InternetExplorerOptions();
opt.merge(capabilities);
WebDriver driver = new InternetExplorerDriver(opt);

How to enable or disable geolocation by selenium test case

I want to allow/block my current location accessible to site by clicking on allow button of that popUp, my chrome version is 62.0, chrome driver version is 3.6.0 and I am using ubuntu 16.04 and my code snippet is,
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
options.addArguments("start-maximized");
options.addArguments("--disable-geolocation");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
driver = new ChromeDriver(capabilities);
But this is not working, could anyone suggest me the perfect solution for this?
Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
Use java.awt.Robot class for this, first test manually and then you can change the key handlers as needed.
For those looking for a way to do it without out robot, you can do it with options:
To deny set profile.default_content_setting_values.geolocation to 1, to auto accept set to 2 (which seems to the current default)
ChromeOptions options = new ChromeOptions();
ArrayList<String> opArgList = new ArrayList<>(); // using an array list (so we can extend it with other passed in options)
opArgList.add("--no-sandbox");
opArgList.add("--disable-dev-shm-usage");
String[] opArg = opArgList.toArray(new String[0]);
HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.geolocation", 1);
options.setExperimentalOption("prefs", prefs);
options.addArguments(opArg);
driver = new RemoteWebDriver(new URL("http://localhost:4444/"), options);

Categories

Resources