How to start IE in private mode in c# with selenium webdriver - c#

I'm starting using selenium Webdriver with c# and Visualstudio.
I would like to start Internetexplorer in private mode. So I have not to care about old browsing data during my test.
I searched for quite a long time now to find how to do this.
Sadly I could not find a solution.
Could anybody provide me with a working code snippet showing how to start IE in private mode from c# code?
I used the following command to start the browser normally:
Context.Instance.Driver = new InternetExplorerDriver();
I tried to add this to make it work:
InternetExplorerOptions options = new InternetExplorerOptions();
options.BrowserCommandLineArguments = "--private";
Context.Instance.Driver = new InternetExplorerDriver(options);
This was niether a success.
Finally, I tried this also:
InternetExplorerDriverService service = InternetExplorerDriverService.CreateDefaultService();
service.SuppressInitialDiagnosticInformation = true;
InternetExplorerOptions options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.BrowserCommandLineArguments = "-private";
Context.Instance.Driver = new InternetExplorerDriver(service, options);
I would like to have IE running in private mode for my tests.

Here, InternetExplorerOptions Members page; it is stated that BrowserCommandLineArguments property only has an effect when the ForceCreateProcessApi is true. ForceCreateProcessApi default value is false.
Would you please try to set it manually?
options.ForceCreateProcessApi = true;
options.BrowserCommandLineArguments = "-private";

Related

Selenium Webdriver C# - redirect chromedriver.log to stdout or stderr

I'm trying to redirect Chromedriver logs from saving to chromedriver.log to stdout, as it's done in Geckodriver and MSEdgeDriver, so that I can view the logs in build logs of CI (TeamCity). As mentioned in the title, I'm using C# bindings. My current code is
private IWebDriver ResolveChromeDriver()
{
var service = ChromeDriverService.CreateDefaultService();
service.EnableVerboseLogging = true;
var options = new ChromeOptions();
options.SetLoggingPreference(LogType.Driver, LogLevel.All);
options.AddArgument("--verbose");
return new ChromeDriver(service, options);
}
It doesn't work though. Is there any other way to perform it?

Change PhantomJS proxy settings while running

I'm using Selenium and PhantomJs in a C#/Winforms application.
I have to set the proxy for PhantomJS before running it with this code:
var driverService = PhantomJSDriverService.CreateDefaultService("phantomjsdriver");
Proxy proxy = new Proxy();
proxy.HttpProxy = string.Format("xx.xx.xx.xx:port");
driverService.ProxyType = "http";
driverService.Proxy = proxy.HttpProxy;
driverService.AddArgument(string.Format("--proxy-auth={0}:{1}", "username", "password"));
using (var driver = new PhantomJSDriver(driverService))
{
//......
}
Now I have a list of proxies! And I need to change the proxy after each request, So what I do now is just quitting the driver then run it again with a new proxy.
It's not a very efficient way so I was wondering if there was any method to change the proxy without quitting the driver!
Thanks in advance!
EDIT
So there is a function in PhantomJS that enable us to change the proxy at any time.
Any idea how to use it under Selenium?
I found the solution, After finding that PhantomJS has a setProxy function, It was just a matter of how to use it:
String script = "return phantom.setProxy(\"{0}\", {1}, \"http\", \"{2}\", \"{3}\")";
string func = string.Format(script, ppp.IP, ppp.Port, ppp.Username, ppp.Password);
Object obj = driver.ExecutePhantomJS(func);
Hope this code helps someone else!

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 { }
}

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