Open a new tab in an existing browser session using Selenium

My current code below in C# opens a window then navigates to the specified URL after a button click.

protected void onboardButton_Click(object sender, EventArgs e)
{
   IWebDriver driver = new ChromeDriver();
   driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
   driver.Navigate().GoToUrl("https://www.google.com")
}

But the site that I am planning to navigate to has single sign-on. How can I open a new tab in my existing browser session and navigate from there? The above code does not seem to work.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Sending Keys.Control + "t" didn’t work for me. I had to do it with javascript and then switch to it.

((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());

Method 2

To handle new tab you should switch to it first. Try following:

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

Also you might need to switch back:

driver.SwitchTo().Window(driver.WindowHandles.First());

Method 3

This may not works:

driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");

Alternative: Find clickable element with target blank (search for “blank” in page’s surce code). This will open new tab.

Than switch between tabs (thanks @Andersson) with:

driver.SwitchTo().Window(driver.WindowHandles.Last());
driver.SwitchTo().Window(driver.WindowHandles.First());

Method 4

We can simulate Ctrl + Element Click

Actions action = new Actions(_driver);
action.KeyDown(Keys.Control).MoveToElement(body).Click().Perform();

Reference:
https://www.codeproject.com/Answers/1081051/Open-link-in-New-tab-using-Selenium-Csharp-for-chr#answer3

Method 5

The solution is really simple:

Driver.SwitchTo().NewWindow(WindowType.Tab);

Enjoy…

Method 6

IWebDriver driver = new ChromeDriver();

Change this to:

var driver = new ChromeDriver();

I do not know why. May be the IWebDriver miss the method.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x