Open Internet Explorer in Private Mode with Selenium - c#

So I've been trying to open IE in Private using selenium (C#), this is the closest i've come so far:
InternetExplorerOptions op = new InternetExplorerOptions();
op.PageLoadStrategy = PageLoadStrategy.Normal;
op.IgnoreZoomLevel = true;
op.InitialBrowserUrl = "https://entry.wgrintra.net/schadenwv/servlet/main";
op.ForceCreateProcessApi = true;
op.BrowserCommandLineArguments = "-private";
IWebDriver driver = new InternetExplorerDriver(op);
The problem here is, after 60 seconds of opening the browser (correctly in private) the driver times out (last step doesn't finish).
I've looked around a lot, most is just using Capabilities which are not useful anymore.
(I had to add a value to the registry to be able to forcecreate the process api)

Try to refer code example below and make a test with it on your side may help to solve your issue.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* Created by Amol Chavan on 9/19/2016.
*/
public class PrivateBrowsing {
public static void main(String args[]){
createInstance();
}
public static WebDriver createInstance(){
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true);
capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
System.setProperty("webdriver.ie.driver","C:\\Grid\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get("http://www.google.com");
return driver;
}
}
Reference:
How to Open Internet Explorer Browser in Incognito / Private mode using Selenium / WebDriver ?

Related

How to launch a specific URL with Firefox in C#

I'm trying to launch a specific URL using Firefox. But I'm only able to open Firefox browser and not able to launch that URL.
class BrowserHelper
{
IWebDriver driver;
string path = Path.Combine(Environment.CurrentDirectory, #"gecko\\");
public void Navigate(string url)
{
path = path.Replace(#"\", #"\\");
var driverService = FirefoxDriverService.CreateDefaultService(path);
driverService.HideCommandPromptWindow = true;
if (driver == null)
{
driver = new FirefoxDriver(driverService);
}
driver.Url = url;
driver.Navigate().GoToUrl(driver.Url);
driver.Manage().Window.Maximize();
}
}
class Realtest
{
BrowserHelper BH = new BrowserHelper();
public void test()
{
string search ="apple";
BH.Navigate("https://www.google.com/search?q=" + search);
}
}
And I can only get this page:
Here's the final URL I want to launch: https://www.google.com.sg/search?q=apple
Any suggestions? Thanks in advance.
I have tried the below code (in Java), and it's working fine by launching the browser and loading the URL also.
System.setProperty("webdriver.gecko.driver","Drivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com.sg/search?q=apple");
So I feel the problem is with geckodriver version and FireFox browser installed in your local machine. I would suggest you update FireFox and geckodriver to the latest version.
There is also a pretty easy solution using the command line with c#.
Simply execute the following command to open a new Firefox Tab with the given URL:
start firefox wikipedia.de
You can also start a new Firefox instance if you wish:
start firefox -new-instance wikipedia.de
Last but not least the .Net Code to execute the commands in CLI:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
Arguments = "/c start firefox wikipedia.de",
CreateNoWindow = true,
FileName = "CMD.exe"
});
There is also a lot of other stuff that can be done with Firefox commandLine paramters. You an find all of them here:
https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=Command_Line_Options
This also works with chrome and opera, simply call
start opera wikipedia.de
instead of firefox.
You do not need to set driver.Url, remove that line.
driver.Navigate().GoToUrl(url);
driver.Manage().Window.Maximize();
Also, if you simply want to launch a single URL without interacting with the page, then Selenium is overkill.

Selenium Why setting acceptuntrustedcertificates to true for firefox driver doesn't work?

I'm developping some selenium tests and I face an important issue because I didn't found a "real" solution when I test my site with secure connection (HTTPS). All solutions I found on stackoverflow are out of date or doesn't work:
I am writing a Selenium script in Firefox but I am getting "Untrusted Certificate"
How to disable Firefox's untrusted connection warning using Selenium?
Handling UntrustedSSLcertificates using WebDriver
The only workaround I have is to use the nightly mozilla release as indicated on github: https://github.com/mozilla/geckodriver/issues/420
private IWebDriver driver;
private string baseURL;
private FirefoxOptions ffOptions;
private IWait<IWebDriver> wait;
[SetUp]
public void SetupTest()
{
ffOptions = new FirefoxOptions();
ffOptions.BrowserExecutableLocation = #"D:\AppData\Local\Nightly\firefox.exe";
FirefoxProfile profile = new FirefoxProfile();
profile.AssumeUntrustedCertificateIssuer = false;
profile.AcceptUntrustedCertificates = true;
ffOptions.Profile = profile;
ffOptions.LogLevel = FirefoxDriverLogLevel.Info;
driver = new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), ffOptions, TimeSpan.FromSeconds(30));
//[...]
}
Configuration:
Firefox v47.0.1, v49.0.2, v51.0.1, v52.0b9 (i tried these differents versions)
geckodriver 0.14
selenium 3.1.0
Does anyone have a solution to avoid using nightly release ?
For information I have access only to stackoverflow and github due to my internet policy, and please don't suggest me to use chrome!
Thank for your help!
Yeah, it's a bug on the geckodriver. You can find it here!
Setting the AcceptInsecureCertificates property to true in the FirefoxOptions fixed this problem for me. Here's what my initialization looked like after this change:
var profile = new FirefoxProfile();
profile.DeleteAfterUse = true;
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris", LocalURL);
profile.SetPreference("network.automatic-ntlm-auth.allow-non-fqdn", true);
profile.SetPreference("webdriver_accept_untrusted_certs", true);
// Only setting this property to true did not work for me either
profile.AcceptUntrustedCertificates = true;
profile.AssumeUntrustedCertificateIssuer = false;
return new FirefoxDriver(new FirefoxOptions
{
Profile = profile,
// When I also added this line, it DID work
AcceptInsecureCertificates = true
});

How to execute Selenium Chrome WebDriver in silent mode?

When using Chrome Selenium WebDriver, it will output diagnostic output when the servers are started:
Started ChromeDriver (v2.0) on port 9515
I do not want to see these messages, how can I suppress them?
I do this
ChromeOptions options = new ChromeOptions();
options.AddArgument("--silent");
IWebDriver Driver = new ChromeDriver(options);
But diagnostic output is not suppress.
I simply do this
ChromeOptions options = new ChromeOptions();
options.AddArgument("--log-level=3");
IWebDriver driver = new ChromeDriver(options);
Good question, however, I don't know where you got that .AddArgument("--silent"); thing, as that's Chrome's command line switch, not for ChromeDriver. Also, there isn't a Chrome switch called --silent anyway.
Under OpenQA.Selenium.Chrome namespace, there is class called ChromeDriverService which has a property SuppressInitialDiagnosticInformation defaults to false. Basically what you might want to do is to create
ChromeDriverService and pass it into ChromeDriver's constructor. Please refer to the documentation here.
Here is the C# code that suppresses ChromeDriver's diagnostics outputs.
ChromeOptions options = new ChromeOptions();
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.SuppressInitialDiagnosticInformation = true;
IWebDriver driver = new ChromeDriver(service, options);
EDIT:
ChromeDriver (not Chrome) has a command line argument --silent, which is supposed to work. SuppressInitialDiagnosticInformation in .NET binding does exactly that. However, it seems only suppress some of the messages.
Here is a closed chromedriver ticket:
Issue 116: How to disable the diagnostic messages and log file from Chrome Driver?
For me no one of previous answers did not help , my solution was:
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverLocation);
service.SuppressInitialDiagnosticInformation = true;
service.HideCommandPromptWindow = true;
var driver = new ChromeDriver(service, options);
For me the only thing that worked for
selenium-chrome-driver-2.48.2.jar
chromedriver 2.20
selenium-java-2.48.2.jar
was
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver(options);
try this code it will hide browser with "headless" Argument but Chrome ver should > 58
( and even you can hide command prompt window )
IWebDriver driver;
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArgument("test-type");
options.AddArgument("--ignore-certificate-errors");
options.AddArgument("no-sandbox");
options.AddArgument("--headless");//hide browser
ChromeDriverService service = ChromeDriverService.CreateDefaultService(#"chromedriverExepath\");
service.SuppressInitialDiagnosticInformation = true;
//service.HideCommandPromptWindow = true;//even we can hide command prompt window (with un comment this line)
options.BinaryLocation = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
driver = new ChromeDriver(service, options);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://www.example.com");
For anyone finding themselves here wanting a Java solution, there is a thread here:
Selenium chromedriver disable logging or redirect it java
To run Chrome browser with Selenium in console in completely silent mode, you should use this snippet:
options = Options()
options.headless = True
options.add_experimental_option("excludeSwitches", ["enable-logging"])
That trick will suppress any console message from either the Selenium driver or the browser itself, including the first message DevTools listening on ws://127.0.0.1 at the very start.
only add below line
System.setProperty("webdriver.chrome.silentOutput", "true");
output:-
ChromeDriver was started successfully.
Jun 28, 2022 10:38:55 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
This code works fine for me:
public static IWebDriver Driver { set; get; }
-----
Driver = CreateBrowserDriver();
////////////// Create Driver
private static IWebDriver CreateBrowserDriver()
{
try
{
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArgument("--headless"); // HIDE Chrome Browser
var service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true; // HIDE Chrome Driver
service.SuppressInitialDiagnosticInformation = true;
return new OpenQA.Selenium.Chrome.ChromeDriver(service, options);
}
catch
{
throw new Exception("Please install Google Chrome.");
}
}
////////////// Exit Driver
public static void ExitDriver()
{
if (Driver != null)
{
Driver.Quit();
}
Driver = null;
try
{
// Chrome
System.Diagnostics.Process.GetProcessesByName("chromedriver").ToList().ForEach(px => px.Kill());
}
catch { }
}

Using a specific Firefox profile in Selenium WebDriver in C#

I am trying to use a profile I already have set up for firefox with selenium 2 but there is no documentation for C#. The code I have attempted is as follows:
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile(profileName);
driver = new FirefoxDriver(profile);
Code that I have seen that is comparible in Java uses ProfilesIni instead of FirefoxProfileManager, but that is not available in C#. When setting up the driver in this way the selenium profile used has all the default settings instead of the settings specified in the profile I am trying to point to.
I am not sure that I am using the correct methods to retrieve the profile, but if anyone has used Selenium 2 with C#, any information would be helpful.
We use such method to load default firefox profile (you can create custom profile and load it):
private IWebDriver driver;
string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%APPDATA%") + #"\Mozilla\Firefox\Profiles"; // Path to profile
string[] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly);
if (pathsToProfiles.Length != 0)
{
FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0]);
profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need
driver = new FirefoxDriver(new FirefoxBinary(), profile, serverTimeout);
}
else
{
driver = new FirefoxDriver();
}
We had the same problem that the profile wouldn't load. The problem is in FirefoxProfile (line 137). It only looks for user.js and the profile from Firefox is actually prefs.js
137>> File prefsInModel = new File(model, "user.js");
Hack solution: rename prefs.js --> user.js
The following worked for me. I had to specifically set the "webdriver.firefox.profile" preference in order to get it to work.
var allProfiles = new FirefoxProfileManager();
if (!allProfiles.ExistingProfiles.Contains("SeleniumUser"))
{
throw new Exception("SeleniumUser firefox profile does not exist, please create it first.");
}
var profile = allProfiles.GetProfile("SeleniumUser");
profile.SetPreference("webdriver.firefox.profile", "SeleniumUser");
WebDriver = new FirefoxDriver(profile);
I have the same issue, it is not a duplicate.
I am using the following which works
private IWebDriver Driver;
[Setup]
public void SetupTest()
{
string path = #"C:\Users\username\AppData\Local\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);
}
After using the aforementioned answers I had no result, so I tried the following alternate way:
First, create the desired profile by typing about:profiles on Firefox address bar.
Second, the C# code. Note that the profile name we created on first step is passed as an argument.
public IWebDriver driver { get; set; }
public Selenium(String nombrePefil)
{
if (this.driver == null)
{
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("--profile " + nombrePefil);
this.driver = new FirefoxDriver(options);
}
}
I also encountered the same issue, and after searching and trying many different combinations I was able to get Selenium to load a specific profile when using the RemoteWebDriver.
Grid configuration
I launch the HUB using a batch file containing the following
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar C:\Downloads\Selenium\selenium-server-standalone-2.20.0.jar -role hub -maxSession 50 -Dwebdriver.firefox.profile=Selenium
I launch one or more nodes using a batch file containing the following (each node has a unique port number):
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar selenium-server-standalone-2.20.0.jar -role node -hub http://127.0.0.1:4444/grid/register -browser browserName=firefox,platform=WINDOWS,version=11.0,maxInstances=2 -maxSession 2 -port 5555 -Dwebdriver.firefox.profile=Selenium
The key here is the last part of those commands, which needs to match the name of the custom profile you have created.
Code to create WebDriver instance
private readonly Uri _remoteWebDriverDefaultUri = new Uri("http://localhost:4444/wd/hub/");
private IWebDriver CreateFireFoxWebDriver(Uri remoteWebDriverUri)
{
var desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.SetCapability(CapabilityType.BrowserName, "firefox");
desiredCapabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
desiredCapabilities.SetCapability(CapabilityType.Version, "11.0");
var drv = new RemoteWebDriver(remoteWebDriverUri ?? _remoteWebDriverDefaultUri, desiredCapabilities);
return drv;
}
NOTE: The capabilities need to match those of the nodes you are running in the grid.
You can then call this method passing in the Uri of the hub, or null to default to localhost.
Seems fine with the Roaming profile rather than the local profile.
string path = #"C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Is there any way to maximize the browser window using WebDriver (Selenium 2) with C#?
driver.Manage().Window.Maximize();
This works for IE and Firefox. Chrome does not work. There is a bug submitted for this on ChromeDriver project.
Meanwhile, the get around for the chrome is to implement what Joey V. and Coder323 suggested.
ChromeOptions options = new ChromeOptions();
options.addArgument("--start-maximized");
driver = new ChromeDriver(options);
Java
driver.manage().window().maximize();
Python
driver.maximize_window()
Ruby
#driver.manage.window.maximize
OR
max_width, max_height = driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
#driver.manage.window.resize_to(max_width, max_height)
OR
target_size = Selenium::WebDriver::Dimension.new(1600, 1268)
#driver.manage.window.size = target_size
For IE and Firefox:
driver.manage().window().maximize();
For Chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver( options )
There's an outstanding issue to add this functionality to WebDriver, which can be tracked here: http://code.google.com/p/selenium/issues/detail?id=174
A workaround would be to use the JavascriptExector as follows:
public void resizeTest() {
driver.Navigate().GoToUrl("http://www.example.com/");
((IJavaScriptExecutor)driver).ExecuteScript("window.resizeTo(1024, 768);");
}
Test step/scenario:
1. Open a browser and navigate to TestURL
2. Maximize the browser
Maximize the browser with C# (.NET):
driver.Manage().Window.Maximize();
Maximize the browser with Java :
driver.manage().window().maximize();
Another way to do with Java:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenResolution = new Dimension((int)
toolkit.getScreenSize().getWidth(), (int)
toolkit.getScreenSize().getHeight());
driver.manage().window().setSize(screenResolution);
You can use something like this (C#):
driver.Manage().Window.Size = new Size(1024, 768);
If you are using the Chrome Driver you can set the capabilities
var capabilities = new DesiredCapabilities();
var switches = new List<string>
{
"--start-maximized"
};
capabilities.SetCapability("chrome.switches", switches);
new ChromeDriver(chromedriver_path, capabilities);
Simply use Window.Maximize() command
WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
It will work in IE, Mozilla, Chrome
The following Selenium Java code snippet worked for me:
driver.manage().window().setPosition(new Point(0,0));
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(dim);
I had the same problem, but the problem can be solved by using following code.
driver.manage().window().fullscreen();
For C#:
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
We have observed bug with new driver libraries. You can use slightly old jars which are able to handle new browsers versions.
The main generic option is :-
driver.manage().window().maximize();
You can also use other option for maximizing the browser window.
Example:-
Add below option and pass it to driver:-
chromeOptions.addArguments("--start-maximized");
The full code will look like below :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = new ChromeDriver(chromeOptions);
OR
Toolkit toolkit = Toolkit.getDefaultToolkit();
int Width = (int) toolkit.getScreenSize().getWidth();
int Height = (int)toolkit.getScreenSize().getHeight();
//For Dimension class, Import following library "org.openqa.selenium.Dimension"
driver.manage().window().setSize(new Dimension(Width,Height));
driver.get("https://google.com");
Try this on safari :-
JavascriptExecutor jse = (JavascriptExecutor)driver;
String screenWidth = jse.executeScript("return screen.availWidth").toString();
String screenHeight = jse.executeScript("return screen.availHeight").toString();
int intScreenWidth = Integer.parseInt(screenWidth);
int intScreenHeight = Integer.parseInt(screenHeight);
Dimension d = new Dimension(intScreenWidth, intScreenHeight);
driver.manage.window.setSize(d);
using System.Windows.Forms;
using System.Drawing;
public static void MaximizeBrowser(this IE myBrowser)
{
myBrowser.SizeWindow(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
}
I used Jim's code, but slightly modified for use with WatiN and C# to maximize the browser.
You can use Selenium Emulation in WebDriver:
selenium = new WebDriverBackedSelenium(driver,url);
selenium.windowMaximize();
I used this solution
OpenQA.Selenium.Chrome.ChromeOptions chromeoptions = new OpenQA.Selenium.Chrome.ChromeOptions();
chromeoptions.AddArgument("--start-maximized");
OpenQA.Selenium.Chrome.ChromeDriver chrome = new OpenQA.Selenium.Chrome.ChromeDriver(chromeoptions);
For Chrome
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(options);
driver.Manage().Window.Maximize();
There is a function that you can use to maximize the window in Python which is window_maximize(). And this is how I'm using it.Hope this helps -
from selenium import selenium
sel = selenium('localhost', 4444, '*firefox', 'http://10.77.21.67/')
sel.start()
sel.open('/')
sel.wait_for_page_to_load(60000)
#sel.window_focus()
sel.window_maximize()
png = sel.capture_screenshot_to_string()
f = open('screenshot.png', 'wb')
f.write(png.decode('base64'))
f.close()
sel.stop()
C# client drivers:
driver = new FirefoxDriver(firefoxProfile);
driver.Manage().Window.Size = new System.Drawing.Size(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width+10, System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height+10);
===> also add a reference to the .NET assembly "System.Windows.Forms"
... the only problem is that it's not positioned correctly
... please comment if you can correct this
Here's what worked for me in C#, firefoxDriver is global to the class:
in the usings:
using System.Drawing;
using System.Windows.Forms;
in the code:
this.firefoxDriver = new FirefoxDriver();
this.firefoxDriver.Manage().Window.Position = new Point(0, 0);
this.firefoxDriver.Manage().Window.Size = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
For Webdriverjs (node.js), the following maximizes chrome window.
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().window().maximize();
driver.get('hxxp://localhost:8888');
This option is fine for me :
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
This option works on all OS.
The below line of code would maximize IE, Chrome and Mozilla
driver.manage().window().maximize();
The above line of code and other workarounds mentioned in the post did not work for NodeWebKit browser, so as a workaround i had to use native C# code as mentioned below:
public static void MaximiseNWKBrowser(IWebDriver d)
{
var body = UICommon.GetElement(By.TagName("body"), d);
body.Click();
string alt = "%";
string space = " ";
string down = "{DOWN}";
string enter = "{ENTER}";
SendKeys.SendWait(alt + space);
for(var i = 1; i <= 6; i++)
{
SendKeys.SendWait(down);
}
SendKeys.SendWait(enter);
}
So this workaround basically uses "ALT+SPACE" to bring up the browser action menu to select "MAXIMIZE" from the options and presses "ENTER"
Through the below code i'm able to maximize the window,
((JavascriptExecutor) driver).executeScript("if(window.screen){
window.moveTo(0, 0);
window.resizeTo(window.screen.availWidth, window.screen.availHeight);
};");
This is working fine for me.
Capybara.current_session.driver.browser.manage.window.resize_to(1800, 1000)
I tried many of the answers above, but none work well.
My chrome driver version is 2.7 and Iam using selenium-java vesion is 2.9.0.
The official document suggests using:
var capabilities = new DesiredCapabilities();
var switches = new List<string>
{
"--start-maximized"
};
capabilities.SetCapability("chrome.switches", switches);
new ChromeDriver(chromedriver_path, capabilities);
The above also does not work. I checked the chrome driver JsonWireProtocol:
http://code.google.com/p/selenium/wiki/JsonWireProtocol
The chrome diver protocol provides a method to maximize the window:
/session/:sessionId/window/:windowHandle/maximize,
but this command is not used in selenium-java. This means you also send the command to chrome yourself. Once I did this it works.
Chrome driver already support:
Java:
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
For me, none of the solutions above worked when working with Selenium Web Driver C# + Chrome:
window.resizeTo(1024, 768); - I want to use the whole screen
--start-maximized - it is ignored
driver.manage().window().maximize(); - does not work because it requires some extension and I am not allowed to use Chrome extensions
I managed to get it working using InputSimulator:
var inputSim = new InputSimulator();
// WinKey + UP = Maximize focused window
inputSim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.UP);
You can try with this code to maximize chrome window.
ChromeOptions options = new ChromeOptions();
options.addArguments("--window-size=1920,1080");
WebDriver driver = new ChromeDriver(options);

Categories

Resources