Sunday, March 27, 2016

Selenium WebDriver in C#: Switch To new window or tab

There are many instances when you click on a link and it opens a new window or tab. Selenim WebDriver provides a way to switch to that new window using SwitchTo() method.
See the code below
 
IWebDriver driver = new new FirefoxDriver();

//perform some action to open a new window. Like clicking a link.
driver.FindElement(By.Id("btnId")).Click();

//switch to new window.
driver.SwitchTo().Window(driver.WindowHandles.Last());

//if you want to switch back to your first window
driver.SwitchTo().Window(driver.WindowHandles.First());
I hope this little code snippet will help you in your future automation :)

2 comments:

Testing Challenge

Can you find more than 20 defects in the below image? Write your defects in the comments section.