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 :)

1 comment:

  1. It worked for me. I love it man!

    ReplyDelete