Tuesday, 4 August 2015

Switch between windows or tabs in Selenium Webdriver

Please refer the below set of code to understand how can we switch between different windows in Selenium. Open a web page:

WebDriver driver = new FirefoxDriver();
driver.get("http://qtpseleniumsolutions.blogspot.in/");

Open a new window:
WebElement elemLink = driver.findElement(By.linkText("Web Driver"));
Actions actions = new Actions(driver);
actions.moveToElement(elemLink);
actions.contextClick(elemLink).sendKeys(Keys.ARROW_DOWN)
  .sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build()
  .perform();
For opening in a new tab/window see the post Open in new Tab or new Window in Selenium Webdriver

Switch between two tabs or windows:

If you want to switch to a specific window, see below:
String windowHandle = driver.getWindowHandle();






Now if you want to switch to second windows use the below code:

for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

Switch to the parent window:

driver.switchTo().window(windowHandle);

Or, simply you can do as below to switch between two tabs or windows: 10
ArrayList<string> tabs = new ArrayList<string> (driver.getWindowHandles());

//Switch to new window
driver.switchTo().window(tabs.get(1));
driver.close();//do some action in new window(2nd tab)

//Switch to main/parent window
driver.switchTo().window(tabs.get(0));
driver.getTitle();//do some action in main window(1st tab)
</string></string>

No comments:

Post a Comment