C Sharp with Selenium - How to Switch one tab to another tab in Csharp Selenium?



We can switch one tab to another tab with Selenium webdriver in C#.

Sometimes on clicking a link or a button, we can have multiple tabs opened in the same browser.

By default, the webdriver can access only the parent tab. To access the second tab, we have to switch the driver focus with the help of the SwitchTo().Window() method. The window handle id of the tab where we want to switch to is passed as a parameter..

The method CurrentWindowHandle yields the window handle id of the tab which is in focus. The WindowHandles method returns all the window handle ids of the opened tabs in the browser.

Let us try to switch the tabs opened in browser as shown in below image −

Syntax

driver.SwitchTo().Window(driver.WindowHandles[1]);

Example

using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using System; using OpenQA.Selenium; namespace NUnitTestProject2{    public class Tests{       String url =" https://www.tutorialspoint.com/index.htm";       IWebDriver driver;       [SetUp]       public void Setup(){          //creating object of FirefoxDriver          driver = new FirefoxDriver("");       }       [Test]       public void Test2(){          //implicit wait          driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);          //URL launch          driver.Navigate().GoToUrl(url);          //identify element then click          IWebElement l = driver.FindElement(By.XPath("//*[text()='Jobs']"));          l.Click();          //switch to second tab          driver.SwitchTo().Window(driver.WindowHandles[1]);          //get current window handle id          Console.WriteLine          ("Current window id: " + driver.CurrentWindowHandle);          Console.WriteLine("Page title in second tab is: " + driver.Title);          //close second tab          driver.Close();          //switch to first tab          driver.SwitchTo().Window(driver.WindowHandles[0]);          IWebElement m = driver.FindElement(By.TagName("h4"));          Console.WriteLine("Element in first tab is: " + m.Text);       }       [TearDown]       public void close_Browser(){          driver.Quit();       }    } }

Output

Updated on: 2021-04-07T08:47:13+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements