How do you automatically open the Chrome Devtools tab within Selenium (C#)? - google-chrome

I see that there's a relatively new option to open Chrome with Devtools open from the command line, which I have gotten to work from my Windows 8.1 command line using a call like this:
c:\Program Files (x86)\Google\Chrome\Application>"chrome.exe" --auto-open-devtools-for-tabs
When I try to add this option on the same box when creating my ChromeDriver in Selenium (in C#), however, the option seems to be ignored.
var options = new ChromeOptions();
options.AddArgument("auto-open-devtools-for-tabs");
string executingAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
string driverPath = Path.Combine(Path.GetDirectoryName(executingAssembly), "ChromeWebDriver");
_driver = new ChromeDriver(driverPath, options);
I've tried a few variations on theme to make sure options are working at all, including...
var options = new ChromeOptions();
options.AddArguments(new[] { "start-maximized", "auto-open-devtools-for-tabs"});
... and...
var options = new ChromeOptions();
options.AddArgument("start-maximized");
options.AddArgument("auto-open-devtools-for-tabs");
... and...
var options = new ChromeOptions();
options.AddArgument("start-maximized");
options.AddExcludedArgument("auto-open-devtools-for-tabs");
... as well as setting those with -- in front of each option string. All I get from any of those are maximized windows.
I get the feeling the auto-open-devtools-for-tabs argument's not supported by Selenium's Chrome Web Driver, but I'm not sure why that wouldn't support the same set of options as the "full" app.
Anyone have this option working with Selenium in C#, or know why it shouldn't be working in this case?
This is not unlike this question, but here I'm asking specifically about the auto-open-devtools-for-tabs option with C#. That asker claims not to have had any luck with options, and was asking how to open devtools from "within" Selenium, looking for a method explicitly before this option existed.

I've tried this with in VS 2017, Selenium v3.12.1#, Firefox v60.0.2, Chrome v66, Nunit v3.10.1, Gecko Driver v20.1, and Chrome driver v2.4 (all using C#).
I tried to search for Firefox but did not have any success. I did find a solution for Chrome v66.
Please provide profile like this: options.AddArguments("--auto-open-devtools-for-tabs");
This is a complete chrome driver implementation:
ChromeOptions options = new ChromeOptions();
options.AddArgument("--start-maximized");
options.AddArguments("disable-infobars");
options.AddArguments("--disable-notifications");
options.AddArguments("--auto-open-devtools-for-tabs");
driver = new ChromeDriver(DrivePath, options, TimeSpan.FromSeconds(100));
See also this post: "List of Chromium Command Line Switches"
Below commands are NOT working, this is issue with Geckodriver so Gecko team has to provide some solution or fix for that:
driver.FindElement(By.CssSelector("body")).SendKeys(Keys.F12);
Actions action = new Actions(driver); action.SendKeys(Keys.F12); action.Perform();
Actions action = new Actions(driver); action .KeyDown(Keys.Control)
.SendKeys(Keys.F12).KeyUp(Keys.Control).Perform();
Actions action = new Actions(driver); action.SendKeys(Keys.F12); action.Click();

Following the thread on SO-12212504 and leading from the selected answer.
One of the solution to this would be pressing F-12 [Key F12 Documentation] key using :
// without an element
new Actions(driver).SendKeys(Keys.F12).Perform();
// send keys to body
new Actions(driver).SendKeys(driver.FindElement(By.XPath("//body")), Keys.F12).Perform();
On the other side could you try and use AddUserProfilePreference from amongst the ChromeOptions Methods :
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("auto-open-devtools-for-tabs", "true");
Note : I am not very sure about the parameter name, but I hope you can find something corresponding here.
Edit : Some more attempts using keyboard shortcuts for the same -
Windows : [F12 or Ctrl + Shift + I]
String openDevTools = Keys.chord(Keys.CONTROL, Keys.SHIFT, "I");
driver.FindElement(By.XPath("//body")).SendKeys(openDevTools).Perform();
Mac : [Cmd + Opt + I]
String openDevTools = Keys.chord(Keys.COMMAND, Keys.ALT, "I");
driver.FindElement(By.XPath("//body")).SendKeys(openDevTools).Perform();

Ruby: must have installed latest selenium-webdriver (3.7.0) gem
options1 = Selenium::WebDriver::Chrome::Options.new
options1.add_argument('--auto-open-devtools-for-tabs')
driver = Selenium::WebDriver.for :chrome, options: options1
driver.get("https://stackoverflow.com")

I think the issue is with your options being declared as a var and not ChromeOptions, this code open google.com with dev tools open
public static void Scraps()
{
//Declare options variable and set dev tools argument
ChromeOptions co = new ChromeOptions();
co.AddArguments("--auto-open-devtools-for-tabs");
//Initiate driver instance and go to google.com
IWebDriver driver = new ChromeDriver(co);
driver.Url = "https://www.google.com/";
}

Related

How to automate the maximize the window of an Electron application using Selenium

Currently I am performing End to end testing of an application developed using electron framework. I am able to open the application using selenium and also able to interact wit h the form controls etc. When I open the application it opens in a minimized mode and I want to maximize it by performing the keystrokes ALT + Space + X The following is my code,it executes with out any errors but does not maximize the window.
[TestMethod]
public void TestDispneseLogin()
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.BinaryLocation = #"C:\CorumDispense-win32-x64\CorumDispense.exe";
chromeOptions.AddArgument("start-maximized");
DesiredCapabilities capability = new DesiredCapabilities();
capability.SetCapability(CapabilityType.BrowserName, "Chrome");
capability.SetCapability("chromeOptions", chromeOptions);
IWebDriver driver = new ChromeDriver(chromeOptions);
Thread.Sleep(2000);
//maximize the window
Actions keyAction = new Actions(driver);
keyAction.SendKeys(Keys.Alt);
keyAction.SendKeys(Keys.Space);
keyAction.SendKeys(Convert.ToString('\u0078'));
keyAction.Build().Perform();
//input the text into the patient text box
driver.FindElement(By.Id("patient")).SendKeys("bharat");
}
I have also tried the option
keyAction.KeyDown(Keys.Alt).KeyDown(Keys.Space).SendKeys(Convert.ToString('\u0078')).Perform();
But it fails and gives me the following error
Test Name: TestDispneseLogin
Test FullName: LightHouseTestScenarios.TestScenarios.ElectronTest.TestDispneseLogin
Test Source: C:\Automation\SeleniumProjects\Lighthouse\LightHouseTestScenarios\TestScenarios\ElectronTest.cs : line 83
Test Outcome: Failed
Test Duration: 0:00:05.1098462
Result StackTrace:
at OpenQA.Selenium.Interactions.Internal.SingleKeyAction..ctor(IKeyboard keyboard, IMouse mouse, ILocatable actionTarget, String key)
at OpenQA.Selenium.Interactions.Actions.KeyDown(IWebElement element, String theKey)
at OpenQA.Selenium.Interactions.Actions.KeyDown(String theKey)
at LightHouseTestScenarios.TestScenarios.ElectronTest.TestDispneseLogin() in C:\Automation\SeleniumProjects\Lighthouse\LightHouseTestScenarios\TestScenarios\ElectronTest.cs:line 99
Result Message:
Test method LightHouseTestScenarios.TestScenarios.ElectronTest.TestDispneseLogin threw exception:
System.ArgumentException: key must be a modifier key (Keys.Shift, Keys.Control, or Keys.Alt)
Parameter name: key
I have also tried the below but with no success
keyAction.SendKeys(Keys.Alt + Keys.Space + Convert.ToString('\u0078')).Perform();
and also this option
driver.Manage().Window.Maximize();
Can some one help me solving this issue,thanks in advance.
cheers,
bharadwaj.
When you need using electron features, the easy way to do it is working with the executeScript method.
instead:
driver.Manage().Window.Maximize();
replace with:
driver.executeScript("require('electron').remote.BrowserWindow.getFocusedWindow().maximize();");
For python-selenium implementation, following worked for Electron:
self.session.execute_script('window.moveTo(0, 0);window.resizeTo(screen.width, screen.height);')
It does not exactly maximize the window but sets the window size equal to screen size. Might not work for all types of applications.
try this code.. Its working for me...
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("require('electron').remote.BrowserWindow.getFocusedWindow().maximize();");

Unable to switch to new tab in Chrome in Selenium Webdriver

I have a issue while switching to new tab in chrome, by following some links on internet i came to know it is the issue with Chrome Driver, but i have latest chrome driver(2.21) and updated chrome browser(version 50).
Issue : unknown error: DevTools returned unknown type:webview
(After debugging, i get to know the issue is coming from driver.getWindowHandles();)
Pls help!!!
You should post the code that is giving error, nevertheless, below is the code that can be used to switch between chrome tabs:
System.setProperty("webdriver.chrome.driver",
"D:\\path\\to\\chrome\\exe\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String currWindow = driver.getWindowHandle();
driver.get("https://www.google.com");
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
// Open new tab
Set<String windowsList = driver.getWindowHandles();
for (String str : windowsList) {
if (!str.equals(currWindow)) {
driver.switchTo().window(str);
}
}
driver.get("https://www.facebook.com"); // open facebook

Appium - running browser tests without clearing browser data

I'm testing a web application on Chrome, Android (real device, not emulator) using Appium. Whenever I launch a test, all browser data (bookmarks, history etc.) is deleted. Is there any way to stop this from happening?
I tried setting the noReset capability to true, but that didn't help.
Thank you in advance for any help
public static Uri testServerAddress = new Uri("http://127.0.01:4723/wd/hub"); // Appium is running locally
public static TimeSpan INIT_TIMEOUT_SEC = TimeSpan.FromSeconds(180);
public void SetUpTest()
{
if (driver == null)
{
DesiredCapabilities testCapabilities = new DesiredCapabilities();
testCapabilities.SetCapability("browserName", "Chrome");
testCapabilities.SetCapability("platformName", "Android");
testCapabilities.SetCapability("deviceName", "S(Galaxy S5)");
testCapabilities.SetCapability("noReset", true);
AppUrl = "http://www.google.com/"; //for example
driver = new RemoteWebDriver(testServerAddress, testCapabilities, INIT_TIMEOUT_SEC);
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, globalTimeoutInSec));
driver.Navigate().GoToUrl(AppUrl);
}
}
Chromedriver always starts totally fresh, nothing is keeping.
There is option to re-use the existent one (using desired capability androidUseRunningApp) but unfortunately Appium any way will kill it.
Please see more details in this post

Enabling Chrome Extension in Incognito Mode via CLI flags?

I'm using selenium to test a chrome extension and part of the extension requires the user to be in incognito mode. Currently, I've not been able to enable the extension to be allowed in incognito mode upon startup except by adding the argument user-data-dir=/path/to/directory.
The problem with this is that it loads the extension from the depths of my file system, rather than in a way I can check into git.
I've also tried navigating selenium to the chrome extensions settings page but it seems that selenium can't drive chrome:// pages.
Any ideas on to how to enable incognito on the chrome extension on boot of the chrome driver?
Here is the solution that will work with the latest version of Chrome 74.
Navigate to chrome://extensions
Click on Details button for your desired extension
Copy the url (This contains your extension id)
Now we have to navigate to the above url and then click on the allow in incognito toggle.
Java:
driver.get("chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");
Python:
driver.get("chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai")
driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");
Continue Reading, if you want to know how and why
Root Cause:
As part of enhancements to the chrome browser, google moved all the chrome option in to shadow dom. So you can not access allow in incognito toggle element as selenium find_element method which will point to the original dom of the page. So we have to switch to the shadow dom and access the elements in the shadow tree.
Details:
Shadow DOM:
Note: We will be referring to the terms shown in the picture. So please go through the picture for better understanding.
Solution:
In order to work with shadow element first we have to find the shadow host to which the shadow dom is attached. Here is the simple method to get the shadow root based on the shadowHost.
private static WebElement getShadowRoot(WebDriver driver,WebElement shadowHost) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost);
}
And then you can access the shadow tree element using the shadowRoot Element.
// get the shadowHost in the original dom using findElement
WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS"));
// get the shadow root
WebElement shadowRoot = getShadowRoot(driver,shadowHost);
// access shadow tree element
WebElement shadowTreeElement = shadowRoot.findElement(By.cssSelector("shadow_tree_element_css"));
In order to simplify all the above steps created the below method.
public static WebElement getShadowElement(WebDriver driver,WebElement shadowHost, String cssOfShadowElement) {
WebElement shardowRoot = getShadowRoot(driver, shadowHost);
return shardowRoot.findElement(By.cssSelector(cssOfShadowElement));
}
Now you can get the shadowTree Element with single method call
WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS_Goes_here));
WebElement shadowTreeElement = getShadowElement(driver,shadowHost,"shadow_tree_element_css");
And perform the operations as usual like .click(), .getText().
shadowTreeElement.click()
This Looks simple when you have only one level of shadow DOM. But here, in this case we have multiple levels of shadow doms. So we have to access the element by reaching each shadow host and root.
Below is the snippet using the methods that mentioned above (getShadowElement and getShadowRoot)
// Locate shadowHost on the current dom
WebElement shadowHostL1 = driver.findElement(By.cssSelector("extensions-manager"));
// now locate the shadowElement by traversing all shadow levels
WebElement shadowElementL1 = getShadowElement(driver, shadowHostL1, "#viewManager > extensions-detail-view.active");
WebElement shadowElementL2 = getShadowElement(driver, shadowElementL1,"div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito");
WebElement allowToggle = shadowElementL2.findElement(By.cssSelector("label#label input"));
allowToggle.click();
You can achieve all the above steps in single js call as at mentioned at the beginning of the answer (added below just to reduce the confusion).
WebElement allowToggle = (WebElement) js.executeScript("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input')");
In chrome version 69 this code works (Python version):
driver.get('chrome://extensions')
go_to_extension_js_code = '''
var extensionName = 'TestRevolution';
var extensionsManager = document.querySelector('extensions-manager');
var extensionsItemList = extensionsManager.shadowRoot.querySelector(
'extensions-item-list');
var extensions = extensionsItemList.shadowRoot.querySelectorAll(
'extensions-item');
for (var i = 0; i < extensions.length; i += 1) {
var extensionItem = extensions[i].shadowRoot;
if (extensionItem.textContent.indexOf(extensionName) > -1) {
extensionItem.querySelector('#detailsButton').click();
}
}
'''
enable_incognito_mode_js_code = '''
var extensionsManager = document.querySelector('extensions-manager');
var extensionsDetailView = extensionsManager.shadowRoot.querySelector(
'extensions-detail-view');
var allowIncognitoRow = extensionsDetailView.shadowRoot.querySelector(
'#allow-incognito');
allowIncognitoRow.shadowRoot.querySelector('#crToggle').click();
'''
driver.execute_script(go_to_extension_js_code)
driver.execute_script(enable_incognito_mode_js_code)
Just remember to change var extensionName = 'TestRevolution'; line to your extension name.
If you are trying to enable the already installed extension in incodnito, then try the below code . It should work with chrome.
driver.get("chrome://extensions-frame");
WebElement checkbox = driver.findElement(By.xpath("//label[#class='incognito-control']/input[#type='checkbox']"));
if (!checkbox.isSelected()) {
checkbox.click();
}
I'm still newbie in coding, but I figured another method after looking in chrome's crisper.js at chrome://extensions/ .
First you need to know the extension ID. You can do it by making the id constant here, or using pako's method on obtaining the id's. For mine it's "lmpekldgmhemmmbllpdmafmlofflampm"
Then launch chrome with --incognito and addExtension, then execute the javascript to enable in incognito.
Example:
public class test2 {
static String dir = System.getProperty("user.dir");
static WebDriver driver;
static JavascriptExecutor js;
public static void main(String[] args) throws InterruptedException, IOException{
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
options.addExtensions(new File(dir + "\\randua.crx"));
System.setProperty("webdriver.chrome.driver",dir + "\\chromedriver73.exe");
driver = new ChromeDriver(options);
js = (JavascriptExecutor) driver;
String extID = "lmpekldgmhemmmbllpdmafmlofflampm";
driver.get("chrome://extensions-frame/");
new WebDriverWait(driver, 60).until(webDriver -> js.executeScript("return document.readyState").equals("complete"));
js.executeScript("chrome.developerPrivate.updateExtensionConfiguration({extensionId: \"" + extID + "\",incognitoAccess: true})");
Thread.sleep(1000);
}
}
Hope it helps :)

Unable to Launch Google Chrome using default/custom profile in Selenium WebDriver that undergo http basic authentication

Following methods are not working properly.
Since GRID is used, capability is set as null here.
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
DesiredCapabilities capability=null;
Method 1:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--user-data-dir=C:/Users /username/AppData/Local/Google/Chrome/User Data/Default"));
driver = new ChromeDriver(capabilities);
Method 2:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
String chromeProfile = "C:/Users/username/AppData/Local/Google/Chrome/Application /chrome.exe";
ArrayList<String> switches = new ArrayList<String>();
switches.add("C:/Users/username/AppData/Local/Google/Chrome/User Data/Default" + chromeProfile);
capabilities.setCapability("chrome.switches", switches);
driver = new ChromeDriver(capabilities);
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
If you face such error:
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally
Then try to create a new Chrome profile and execute tests.
Copy the folder, 'User Data'
Paste & Rename the folder on the same location. e.g., New User
Now, locate the directory, C:/Users/user_name/AppData/Local/Google/Chrome/New User
If you like to test the profile, then bookmark some of the sites & observe them on next run.
1 Set the chromedriver property in starting the node. My approach:
java -jar selenium-server-standalone-2.31.0.jar -role node -hub http://localhost:4444/grid/register -maxSession 15 -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=15 -Dwebdriver.chrome.driver=lib\chromedriver.exe
2 Inside the code my approach:
capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"), capabilities);
3 loading the HTTP basic auth page:
String username = "Pavel";
String password = "Omgtoosecrettotellyou";
driver.get("http://" + username + ":" + password + "#" +"your-site.com");