How to set chrome browser window resolution in jenkins - maven

Am running the Selenium webdriver(Maven Project) Scripts through Jenkins by calling pom.xml file. I have set below mentioned browser resolution
driver.manage().window().maximize();
Dimension defaultSize = new Dimension(2560,1440);
driver.manage().window().setSize(defaultSize);
However, while running the scripts through Jenkins, Chrome browser window is not set to the new dimension.
Note : In Local machine it's working fine..

Copied from my question - GOCD pipeline, Selenium ChromeDriver window size is not set
his issue looks to have been caused by two issues,
1- When mvn clean test is run from the IDE this process runs under your current user. However, when run by the Continuous Integration environment, the process is owned by the System process. so does not have the same access to resources.
2 When run from the IDE, chrome will pop up. When run from the CI environment I assumed that it defaulted chrome to run in headless mode. It does not, you have to set the --headless argument so my configuration that now works is as follows
public class GoogleChrome extends Base {
private static final Logger logger = LogManager.getLogger(GoogleChrome.class);
private String rootPath = System.getProperty("user.dir").replace("\\","/");
#Autowired
protected WebDriver driver;
public WebDriver startChromeDriver() {
logger.info("Chrome driver path : " + rootPath + "/../Tools/Drivers/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", rootPath + "/../Tools/Drivers/chromedriver.exe");
Map<String, Object> prefs = new HashMap<String, Object>();
logger.info("Disabling Chrome's credentials service");
prefs.put("credentials_enable_service", false);
logger.info("Disabling Chrome's password manager");
prefs.put("password_manager_enabled", false);
final String regex = "^\\D*$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(System.getProperty("user.name"));
boolean isHuman = matcher.matches();
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
logger.info("Disabling Chrome's info bars");
options.addArguments("disable-infobars");
options.addArguments("--incognito");
options.addArguments("--disable-gpu");
options.addArguments("--no-sandbox");
options.addArguments("--allow-insecure-localhost");
if (isHuman){
logger.info("Chrome starting maximized - isHuman: " +isHuman + " process run by " +System.getProperty("user.name"));
options.addArguments("--start-maximized");
} else {
logger.info("Chrome starting headless - isHuman: " +isHuman + " process run by " +System.getProperty("user.name")) ;
options.addArguments("--headless");
options.addArguments("--window-size=1980,1080");
}
options.setAcceptInsecureCerts(true);
try {
logger.info("Killing Chrome browser");
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
} catch (IOException e) {
logger.error("Task Kill IOException : " + e.getMessage());
}
logger.info("Starting Chrome browser...");
sleep(2);
driver = new ChromeDriver(options);
logger.info("Window size: "+ driver.manage().window().getSize());
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
return driver;
}
}

Chrome disallows setting the size larger than the system's screen resolution width, the problem may be this in your case. Some workaround could be to maximize the window to at least have the largest window available on that system.
While sometimes old chromedriver also cause the issue
If still problem exist then you can change the resolution by chrome option as :
chromeOptions.addArguments("window-size=1936,1056");
Full code will be like :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("window-size=1936,1056");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.co.in/");
Hope it will help you :)

Related

Windows Application Driver, error "Could not find any recognizable digits." when connecting to session (driver)

I know how to launch a windows application using the filepath to launch it and that works (working example below). I am writing tests and they work too but my question is this: If the application is running already, how do I create my "session" (often called "driver") for the currently running application?
I have read this article that explains how you would connect a new session to Cortana which is already running. It's a great example but my app is an exe that has been launched and is not part of windows and I'm getting the error "Could not find any recognizable digits.".
What am I doing wrong?
WORKING CODE THAT LAUNCHES THE APP AND CREATES THE "session":
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
protected static WindowsDriver<RemoteWebElement> session;
public static void Setup(TestContext context)
{
// Launch app and populate session
if (session == null)
{
// Create a new sessio
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", filepath /*The exeecutable's filepath on c drive*/);
//LaunchWPF app and wpf session
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
PROBLEM CODE :
[TestMethod()]
public void Common_CreateSession_ForAlreadyRunningmyApp()
{
string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
IntPtr myAppTopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("MyApp.Client.Shell"))
{
myAppTopLevelWindowHandle = clsProcess.Handle;
}
}
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("appTopLevelWindow", myAppTopLevelWindowHandle);
//Create session for app that's already running (THIS LINE FAILS, ERROR: : 'Could not find any recognizable digits.')
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
There's now an answer on github here. You can see on github I have made 3 tweaks to the answer given by moonkey124, 2 of them were obvious (my aplication name and a little sleep command), 1 of them was to adapt the answer to a WPF application under test...

Chrome headless browser with corporate proxy authetication not working

I am trying to run a Chrome headless browser sitting behind a corporate proxy. I tried below code. But unable to pass through it.
public class HeadlessChrome
{
WebDriver driver;
#Test
public void createChromeDriverHeadless() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:\\LocalData\\workspace\\Drivers and Libraries\\driver\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.setHttpProxy("http://user:pwd#server:port");
proxy.setSslProxy("http://user:pwd#server:port");
// chromeOptions.setCapability("proxy", proxy);
chromeOptions.addArguments("--proxy-server=user:pwd#server:port");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--disable-gpu");
chromeOptions.addArguments("start-maximized");
driver = new ChromeDriver(chromeOptions);
driver.get("http://seleniumhq.org");
Thread.sleep(5000);
System.out.println("Title : " + driver.getTitle());
assertTrue(driver.findElement(By.id("q")).isDisplayed());
driver.quit();
}
}
Please help me out.
If you were not using headless you could have used the approach in below link
user:pass proxies with selenium
But with headless extension are currently not allowed. So now your option is add another proxy
chrome -> (intermediate proxy w/o auth) -> corporate proxy w/ auth -> internet
One options is to use polipo
https://www.irif.fr/~jch/software/polipo/
with below config
parentAuthCredentials=username:password
parentProxy=corporateproxy:port
and then use
chromeOptions.addArguments("--proxy-server=http://polipoproxy:port");
The default would be 127.0.0.1:8123 in don't override in polipo config.
Other options you can use
Use squid proxy instead of polipo
Write your own proxy forwarder using python or node or any other language you are comfortable with
There is headless browser called Linken-sphere who cooperates with Luminati. They some good offers . you should check them up.
https://miped.ru/f/threads/linken-sphere-antidetekt-brauzer-novogo-pokolenija.67098/
It's easy to achieve with selenium 4 (currently in beta). You can do it in multiple ways:
You basically need to register a check for whether to apply the credentials for any request for authorization. Works for both - basic and proxy auth popups.
ChromeDriver driver = new ChromeDriver(new ChromeOptions().setHeadless(true));
String USER_NAME = "guest";
String PASSWORD = "guest";
//register our check here
driver.register(UsernameAndPassword.of(USER_NAME, PASSWORD));
driver.get("https://jigsaw.w3.org/HTTP/");
//Click on the link to show an authentication popup
driver.findElement(By.linkText("Basic Authentication test")).click();
String msg = driver.findElement(By.tagName("html")).getText();
assert msg.equalsIgnoreCase("Your browser made it!");
Using CDP Network domain. Doesn't work for proxy authorization popup (for example here is the similar issue in puppeteer which goes down to the chrome project)
ChromeDriver driver = new ChromeDriver(new ChromeOptions().setHeadless(true));
String USER_NAME = "guest";
String PASSWORD = "guest";
DevTools devTools = driver.getDevTools();
//create a cdp session
devTools.createSession();
//enable network first
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
//Open website
driver.get("https://jigsaw.w3.org/HTTP/");
//Create and send the authorization header
Map<String, Object> headers = new HashMap<>();
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(String.format("%s:%s", USER_NAME, PASSWORD).getBytes()));
headers.put("Authorization", basicAuth);
devTools.send(Network.setExtraHTTPHeaders(new Headers(headers)));
//Click on the link to show an authentication popup
driver.findElement(By.linkText("Basic Authentication test")).click();
String msg = driver.findElement(By.tagName("html")).getText();
assert msg.equalsIgnoreCase("Your browser made it!");
Using the CDP Fetch domain. Works for both - basic and proxy auth popups.
ChromeDriver driver = new ChromeDriver(new ChromeOptions().setHeadless(true));
String USER_NAME = "guest";
String PASSWORD = "guest";
DevTools devTools = driver.getDevTools();
//create a cdp session
devTools.createSession();
//enable Fetch first
devTools.send(Fetch.enable(Optional.empty(), Optional.of(true)));
devTools.addListener(Fetch.requestPaused(), requestPaused -> devTools.send(Fetch.continueRequest(requestPaused.getRequestId(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())));
devTools.addListener(Fetch.authRequired(), authRequired -> devTools.send(Fetch.continueWithAuth(authRequired.getRequestId(), new AuthChallengeResponse(PROVIDECREDENTIALS, Optional.of(USER_NAME), Optional.of(PASSWORD)))));
//Open website
driver.get("https://jigsaw.w3.org/HTTP/");
//Click on the link to show an authentication popup
driver.findElement(By.linkText("Basic Authentication test")).click();
String msg = driver.findElement(By.tagName("html")).getText();
assert msg.equalsIgnoreCase("Your browser made it!");

I am facing issue in executing our Selenium test on safari browser on Mac machine

We are facing issue in switching to the new window on safari browser. Below is our code used for switching the window.
public void switchToWindow() {
Set<String> availableWindows = driver.getWindowHandles();
for (String strWinHandle : availableWindows) {
driver.switchTo().window(strWinHandle);
}
}
In availableWindows, it returns all window handles but instead of switching to new window, it is switching to parent window.
Above code works fine on all other browsers.
Selenium version - 3.11.0
Safari version - 11.1.1
You can try the following code.
public void switchToWindow() {
String curWinHandle = driver.getWindowHandle();
Set<String> availableWindows = driver.getWindowHandles();
for (String strWinHandle : availableWindows) {
if(!curWinHandle.equals(strWinHandle))
driver.switchTo().window(strWinHandle);
}
}

Switch between two windows in selenium webdriver

I am getting error of NoSuchWindowException with this code.I am unable to switch back to old opened window and get back to new window
please review my code and help me.
public void TC_123617()throws InterruptedException {
driver.findElement(By.id("user_login")).sendKeys("akhil");
driver.findElement(By.id("user_pass")).sendKeys("akhil");
driver.findElement(By.id("wp-submit")).click();
Thread.sleep(3000);
driver.findElement(By.cssSelector("#awebsome_oruw-2 > ul")).click();
WebElement userStatus = driver.findElement(By.xpath(".//*[#id='awebsome_oruw-2']/ul/li[11]"));
String parentWindow = driver.getWindowHandle();
driver = new FirefoxDriver();
driver .manage().window().maximize();
driver.get("http://103.16.143.96/incis/wp-login.php");
driver.findElement(By.id("user_login")).sendKeys("manager");
driver.findElement(By.id("user_pass")).sendKeys("manager");
driver.findElement(By.id("wp-submit")).click();
for (String popUpHandle : driver.getWindowHandles()) {
if(!popUpHandle.equals(parentWindow)){
driver.switchTo().window(popUpHandle);
driver.switchTo().window(parentWindow);
}
}
}
You don't need to create a new driver instance if you want to switch between windows using driver.
Save a reference to current window. (so that you can return to perform actions on the window you started from.)
String parentWindow = driver.getWindowHandle();
Next Step, get all the windows and switch to the new window.
List<String> allWindows = driver.getWindowHandles();
for(String curWindow : allWindows){
driver.switchTo().window(curWindow);
}
Now, you can perform any action on the new window, and when done you could close it using
driver.close();
Finally, you can switch back to the parent window to continue your actions using
driver.switchTo().window(parentWindow)

Selenium - how to turn on firebug with console, script and net

I have set up a custom firefox profile and load it when selenium RC starts. The profile has firebug installed, and when I manually launch firefox with that profile, firebug is active. However, when selenium launches that profile, firebug is in the lower right, but it is not enabled. How can I ensure it is enabled at launch? OR, how can I enable it (javascript or ?) - I am using the Java API.
If you create a new Firefox profile and assign it to your driver, you need to set the extensions.firebug.allPagesActivation value of the newly created firefox profile to on.
For example in Ruby, with Capybara:
profile = Selenium::WebDriver::Firefox::Profile.new
profile.add_extension("./firebug-1.10.6.xpi")
profile["extensions.firebug.console.enableSites"] = true
profile["extensions.firebug.net.enableSites"] = true
profile["extensions.firebug.script.enableSites"] = true
profile["extensions.firebug.allPagesActivation"] = "on"
Capybara::Selenium::Driver.new app, :browser => :firefox, :profile => profile
See the documentation for Firebug Preferences
package com.mnas.technology.automation.utility;
import java.io.File;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
/**
* #author manoj.kumar
* #email kumarmanoj.mtech#gmail.com
*/
public class AutomationUtility {
static Logger log = Logger.getLogger(AutomationUtility.class.getName());
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
log.info("Starting Automation...");
log.info("Initializing WebDriver...");
FirefoxProfile ffProfile = new FirefoxProfile();
File firebug = new File(getApplicationPath()+"firebug-2.0.7.xpi");
ffProfile.addExtension(firebug);
ffProfile.setPreference("extensions.firebug.currentVersion", "2.0.7"); //(here you can include the version you currently have)
ffProfile.setPreference("extensions.firebug.showStackTrace", true);
ffProfile.setPreference("extensions.firebug.delayLoad", false);
ffProfile.setPreference("extensions.firebug.showFirstRunPage", false);
ffProfile.setPreference("extensions.firebug.allPagesActivation", "on");
ffProfile.setPreference("extensions.firebug.console.enableSites", true);
ffProfile.setPreference("extensions.firebug.defaultPanelName", "console");
WebDriver driver = new FirefoxDriver(ffProfile);
log.info("WebDriver object activated...");
driver.get("http://www.google.com");
String i = driver.getCurrentUrl();
log.info("CurrentURL===>"+i);
//driver.close();
} catch (Exception e) {
}
}
public static String getApplicationPath()
{
String relPath = System.getProperty("relpath");
return (relPath == null ? System.getProperty("user.dir") : System.getProperty("user.home") + relPath) + File.separatorChar;
}
}
The way to do that is to open Firefox using your custom profile. Right-click on the Firebug icon and select "On for All Web Pages". Close Firefox and you should be good to go! That's how I do it.
Here's what works for me in Python:
fp = webdriver.FirefoxProfile()
fp.add_extension(extension='firebug-2.0.xpi')
fp.set_preference("extensions.firebug.currentVersion", "2.0") #Avoid startup screen
fp.set_preference("extensions.firebug.console.enableSites", "true")
fp.set_preference("extensions.firebug.net.enableSites", "true")
fp.set_preference("extensions.firebug.script.enableSites", "true")
fp.set_preference("extensions.firebug.allPagesActivation", "on")
driver = webdriver.Firefox(firefox_profile=fp)
go to the firefox profile location (which is in your java / c# code)
open firefox from that location.
make all your required settings
close and restart firefox browser this time with your webdriver.
that's it, it solves your problem !!

Resources