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

4 comments:

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

    ReplyDelete
  2. what if we want to handle OS window without using autoIT ?

    ReplyDelete
  3. Hello, It is not working for my workflow, Please help me for below workflow

    1.Open URL, let say abc.com
    2. open second window say xyz.com and switch to this window using above code and it will work as exptected
    3. click download button which is exist in page, it will file download window dialog popup, now I used AUTOIT and able to download by click save button of download
    3 . Open new window and able to switch that new window
    4 closed newly created window and try to switch to 2nd window which had window popup earlier for download, I always get exception of timeout, yes I can increase but it still will not work.

    Can you please help

    ReplyDelete