c# how to find which tab is open for user in selenium 4.4.3

Viewed 43

if the user opens 4 tabs, how can my code find out which tab is currently open for the user to switch to that tab? The codes I use for this work:

private void Timer1_Tick_1(object sender, EventArgs e)
{
    int a = driver.WindowHandles.Count();

    foreach (var handle in driver.WindowHandles) 
    {                                        
        int test = driver.WindowHandles.IndexOf(handle);
        which = // which tab active until the switchto  it???

        driver.SwitchTo().Window(driver.WindowHandles[which]);
    }                  
}
1 Answers

I will give you a very simple example, note that the driver.SwitchTo().NewWindow(WindowType.Tab) works with Selenium 4 and later versions:

string[] searchEngines = { "http://www.bing.com/", "https://google.com", "https://duckduckgo.com" };

driver.Navigate().GoToUrl(searchEngines[0]);
var firstTab = driver.CurrentWindowHandle;

driver.SwitchTo().NewWindow(WindowType.Tab);
driver.Navigate().GoToUrl(searchEngines[1]);
var secondTab = driver.CurrentWindowHandle;


driver.SwitchTo().NewWindow(WindowType.Tab);
driver.Navigate().GoToUrl(searchEngines[2]);
var thirdTab = driver.CurrentWindowHandle;

// Here we select the tab we want by passing the string 
// identifier we already got by calling `driver.CurrentWindowHandle` 
driver.SwitchTo().Window(firstTab);

Related