Selenium c sharp question5: How to switch to browser tab with specific title

Use the following selenium C# script to handle different browser tabs and switch to the tab with specific title:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Threading;

class TabSwitcher
{
static void Main()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(“https://facebook.com”);

// Open new tabs
((IJavaScriptExecutor)driver).ExecuteScript(“window.open(‘https://www.google.com’, ‘_blank’);”);
((IJavaScriptExecutor)driver).ExecuteScript(“window.open(‘https://www.wikipedia.org’, ‘_blank’);”);

Thread.Sleep(2000); // wait for pages to load

string targetTitle = “Google”;
var windowHandles = driver.WindowHandles;

foreach (var handle in windowHandles)
{
driver.SwitchTo().Window(handle);
if (driver.Title == targetTitle)
{
Console.WriteLine(“Switched to: ” + driver.Title);
break;
}
}

Console.WriteLine(“Current URL: ” + driver.Url);
driver.Quit();
}

}

Explanation: In the Main method of the TabSwitcher class, we begin by initializing a ChromeDriver instance and navigating to Facebook using the following line:

driver.Navigate().GoToUrl(“https://facebook.com”);

Next, we open two additional tabs — Google and Wikipedia — using IJavaScriptExecutor, like this

((IJavaScriptExecutor)driver).ExecuteScript(“window.open(‘https://www.google.com’, ‘_blank’);”);
((IJavaScriptExecutor)driver).ExecuteScript(“window.open(‘https://www.wikipedia.org’, ‘_blank’);”);

We then pause execution for 2 seconds to allow the new tabs to load using Thread.Sleep(2000);. However, it’s recommended to use WebDriverWait instead of Thread.Sleep for more reliable and dynamic wait handling.

After that, we define a string variable targetTitle with the value "Google", which represents the title of the tab we want to switch to. We also retrieve all open window handles using:

var windowHandles = driver.WindowHandles;

We then iterate through each window handle using a foreach loop and switch to each window one by one using:

driver.SwitchTo().Window(handle);

Inside the loop, we check whether the current tab’s title matches the target title:

if (driver.Title == targetTitle)
{
Console.WriteLine(“Switched to: ” + driver.Title);
break;
}

If a match is found, we print a confirmation message and exit the loop.

Finally, we close all browser windows and end the WebDriver session using:

driver.Quit();

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x