Selenium C# Open New Tab CTRL+T Not working with CHROME - c#

static void Main()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://google.com");
IWebElement body = driver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Control + "t");
}
This is the code that I am trying to use to open a new tab and its not working, I am not getting any errors nothing, the driver opens Google and thats all....
I have searched a lot and found many tutorials even videos where people are using the exact same code and it works for them, but for me it doesnt and I can't figure it out...
I tried sending Keys.Shift + "t" to the search field and it works, it writes a capital T in the field
I have also tried
Actions act = new Actions(driver);
act.KeyDown(Keys.Control).SendKeys("t").Perform();
And it still does not work, but again if I change Keys.Control to Keys.Shift it writes, seems like nothing that involves Keys.Control is working!!
Edit: I have tried running the code with a IE Driver and it worked there, it opens new tab, but it does not open new tabs on Chrome?

Thanks for the answers! I did it with JavaScript.
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");

Looks like it's a "feature" of the chrome driver.
https://bugs.chromium.org/p/chromedriver/issues/detail?id=581
This is a limitation in the way we simulate keyboard input in ChromeDriver. Keys get sent directly to the render process, bypassing the browser process. So any keyboard shortcut handlers in the browser process will not be invoked by sendKeys().

Try this
driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
driver.SwitchTo().Window(driver.WindowHandles.Last());
driver.Navigate().GoToUrl("http://www.google.com")

If your on a mac, use Keys.Command instead of Keys.Control:
body.SendKeys(Keys.Command + "t");

Related

How to get Selenium to operate two browser windows using only one driver selenium (using c# and chromedriver)?

I am attempting to control two browser windows via selenium using c# and a single chromedriver. The reason being that I need to share session details accross browser windows.
The code that I have tried and failed with is below;
var options = new ChromeOptions();
options.AddArguments("chrome.switches", "--disable-extensions --disable-extensions-file-access-check --disable-extensions-http-throttling --disable-infobars --enable-automation ");
options.AddUserProfilePreference("credentials_enable_service", false);
options.AddUserProfilePreference("profile.password_manager_enabled", false);
options.PageLoadStrategy = PageLoadStrategy.Default;
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var Driver = new ChromeDriver(service, options);
//THIS WILL OPEN A NEW WINDOW. BUT BECAUSE IT IS A NEW DRIVER DOES NOT WORK FOR SHARING SESSION DETAILS.
//var TestDriver = new ChromeDriver(service, options);
//TestDriver.Manage().Window.Maximize();
//THIS JUST OPENS UP A NEW TAB. NOT A NEW WINDOW (IT WOULD SEEM MOST DOCUMENTATION SUGGESTS THAT IT SHOULD)
IJavaScriptExecutor jscript = Driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open();", "google.com.au");
//TRY USING THE SEND KEYS TECHNIQUE. NOTHING HAPPENS
var test = Driver.FindElement(By.TagName("html"));
test.SendKeys(Keys.Control + "n");
test.SendKeys(Keys.Control + "t");
//TRY AGAIN USING THE SEND KEYS TECHNIQUE USING A DIFFERENT TAG. NOTHING HAPPENS
var blah = Driver.FindElements(By.TagName("body"));
blah[0].SendKeys(Keys.Control + "t");
//TRY USING ACTIONS. NOTHING HAPPENS
Actions action = new Actions(Driver);
action.SendKeys(OpenQA.Selenium.Keys.Control + "n");
action.Build().Perform();
I may resort to AutoIt to open a browser if I have to, but one more dependency is not what I need. Documentation everywhere around the web seems to suggest than all the options I tried above should work...I suspect it may be a chromedriver issue of some kind.
Any ideas on how to achieve my goal would be greatly appreciated
UPDATE.
Arnons answer below lead me to the solution. If you are in a similar situation the best thing to do is just open up the browser console (from developers tools) and experiment with javascript until you get what you want. Then just execute that. In the end executing the following code has worked for me.
IJavaScriptExecutor jscript = Driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open('https://www.bing.com.au','_blank','toolbar = 0, location = 0, menubar = 0')");
The other alternative was to use Autoit, which I also got working, much easier than I did figuring out the javascript. But one less dependency is best :)
UPDATE2.
Further complications arise with trying to control the window as an independent browser window. I believe any new window created from a parent window, has the same process id (at least my testing has indicated so), and for all intense and purpose is treated as a tab in the selinium driver. I therefore conclude that certain things are just not possible (for example relocating the child browser window on the screen).
Your first attempt using ExecuteJavaScript was very close, but In order for it to open a new window instead of new tab, you should add the following arguments: `"_blank", "toolbar=0,location=0,menubar=0" to it.
See this question for more details.
I should have read the question better, here is my solution. Ended up using this for selecting windows that popped up after clicking a button but should work with swapping between windows.
//---- Setup Handles ----
//Create a Handle to come back to window 1
string currentHandle = driver.CurrentWindowHandle;
//Creates a target handle for window 2
string popupWindowHandle = wait.Until<string>((d) =>
{
string foundHandle = null;
// Subtract out the list of known handles. In the case of a single
// popup, the newHandles list will only have one value.
List<string> newHandles = driver.WindowHandles.Except(originalHandles).ToList();
if (newHandles.Count > 0)
{
foundHandle = newHandles[0];
}
return foundHandle;
});
//Now you can use these next 2 lines to continuously swap
//Swaps to window 2
driver.SwitchTo().Window(popupWindowHandle);
// Do stuff here in second window
//Swap back to window 1
driver.SwitchTo().Window(currentHandle);
// Do stuff here in first window
You need to explicitly tell Selenium which tab you wish to interact with, which in this case would be;
driver.SwitchTo().Window(driver.WindowHandles.Last());

Which is the correct way to send # to input in selenium?

I am using
email.SendKeys("myemail#gmail.com")
but sometimes is putting myemail2gmail.com, is putting 2 instead of #, I already did a quick research and I would like to know if this is the best solution
email.SendKeys("myemail" + Keys.Shift + "2" + Keys.Shift + "gmail.com");
The issue is in IE 11 and I am using browserstack with specflow in Visual Studio c#.
I've heard about people having issues with sendkeys in combination with special characters in IE and Edge browsers. Indeed, the correct way to do this is:
email.SendKeys("myemail#gmail.com")
If that does not work, you can try using Javascript as a workaround to input the email address into the field. Something like this:
IWebElement email = driver.FindElement(By.Id("email"));
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string script = "arguments[0].setAttribute('value', 'arguments[1]');";
js.ExecuteScript(script, email, "dummy#user.de");
I used something similar than #Agent Shoulder said
var _element= driver.FindElement(By.Id("id"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].setAttribute('value', 'email#gmail.com')", _element);

Selenium ChromeDriver C# - How to send a shortcut browser

How can I send a Chrome shortcut with Selenium ?
I mean shortcuts like Ctrl+S, Ctrl+T or Ctrl+P which has nothing to do with WebElements. I read a lot of similar questions there, but none of the suggested solutions work for me.
Let's say I want to open a new tab (Ctrl+T) on the browser, I tried all the following code without success:
The "standard" way :
IWebElement body = myDriver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Control + "t");
The action way :
Actions action = new Actions(myDriver);
action.SendKeys(Keys.Control + "t").Build().Perform();
The ChromeDriver way 1 :
if(myDriver is ChromeDriver)
{
ChromeDriver chromeDriver = myDriver as ChromeDriver;
chromeDriver.Keyboard.SendKeys(Keys.Control + "t");
}
The ChromeDriver way 2 :
ChromeDriver chromeDriver = myDriver as ChromeDriver;
chromeDriver.Keyboard.PressKey(Keys.Control);
chromeDriver.Keyboard.PressKey("t");
chromeDriver.Keyboard.ReleaseKey(Keys.Control);
chromeDriver.Keyboard.ReleaseKey("t");
Notice that the first way i mentionned worked for me with other WebDriver than Chrome.
I use :
Selenium 3.0.1
ChromeDriver 2.27.440174
And my driver's initialization is really basic :
ChromeOptions options = new ChromeOptions();
this.myDriver = new ChromeDriver(/* my path */, options);
Any ideas?
It seem to be Chromium issue. You cannot use keys combinations with chromedriver, but you still can use JavaScript as alternative:
IJavaScriptExecutor js = myDriver as IJavaScriptExecutor;
js.ExecuteScript("window.open()"); // Open new browser tab like `CTRL + t` do
Unfortunately this issue currently prevents chrome from reacting to shortcuts like Ctrl+T sent by selenium.
I'm using key combinations with Actions just fine. I have been using this code example for years and it works with Chrome, Firefox, and IE.
public void SelectAll()
{
(new Actions(yourDriverInstance)).SendKeys(Keys.Control).SendKeys("a").Perform();
}
Am I missing something???

Selenium getting data from another tab instead of active one

We have a legacy remote system here that dont have webapi, webservice, ...
then we need to do integration by Selenium.
We need open multiple tabs from one master tab to do the extraction but when changing to desired tab and getting value by a css selector it get always the result from the fisrt tab.
Our system cant be opened on internet then i did the same with Google as an example, the same behaviour happens.
Its a bug or my fault ? Someone can see whats is wrong?
Below is a simplified version without error check, its minimal code.
Thanks a lot.
public static void testab()
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("https://www.google.com/ncr");
IWebElement elmTxt = driver.FindElement(By.CssSelector("input#lst-ib"));
elmTxt.SendKeys("google" + Keys.Enter);
IWebElement elmQtdRes = driver.FindElement(By.CssSelector("div#resultStats"));
string strWebStat = elmQtdRes.Text;
IWebElement elmNewsLnk = driver.FindElement(By.CssSelector("a[href*='tbm=nws']"));
elmNewsLnk.SendKeys(Keys.Control + Keys.Return);
IWebElement elmBdy = driver.FindElement(By.CssSelector("body"));
elmBdy.SendKeys(Keys.Control + "2");
elmQtdRes = driver.FindElement(By.CssSelector("div#resultStats"));
string strNewStat = elmQtdRes.Text;
Console.WriteLine("Stat for WEB:[" + strWebStat + "]"); // prints stat for web - OK
Console.WriteLine("Stat for NEWS:[" + strNewStat + "]"); // prints stat for web - WRONG
}
WebDriver will not automatically switch focus to a new window or tab, so we have to tell it when to make the switch.
To switch to the new window/tab, try:
driver.SwitchTo().Window(driver.WindowHandles.Last());
Then, when you are finished on the new tab, close it and switch back to the primary window:
driver.Close();
driver.SwitchTo().Window(driver.WindowHandles.First());
Then from here, you can continue your test.
I'll add a quick disclaimer that I do not have Visual Studio installed on the machine I'm using at the moment and haven't tested the code above. This should, however get you in the right direction.
EDIT: Looking at your code a second time, this example above would replace the SendKeys() call to attempt to switch tab focus:
IWebElement elmBdy = driver.FindElement(By.CssSelector("body"));
elmBdy.SendKeys(Keys.Control + "2");

Call default browser with URL and set a target

I don't know if there is a mechanism to do this: normally one would simply call process start with a URL as the string parameter - has anyone any knowlege or sugestions as to how to add a target?
Google has been singularly unhelpful or else my queries have been a tad useless.
As in the behavior you get with :
link in a new window
Try selenium and WebDriver for C#.
What is the harm in launching the default browser ?
you may do this but what if firefox is not available ! !
ProcessStartInfo proc1 = new ProcessStartInfo("firefox.exe");
proc1.Arguments = "http://www.w3schools.com/tags/att_a_target.asp";
//"http://stackoverflow.com";
Process.Start(proc1);

Categories

Resources