Let me tell you upfront , using Thread.sleep is not good at all, when you run a bunch of test cases.It will slow down the tests and hence it is to be avoided. However, I have used it in my example here, I shall substitute with better wait options sooner .
So here goes the code for toggling between windows.
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class SwitchWindowsDemo {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.navigate()
.to("http://www.toolsqa.com/automation-practice-form/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// This is the parent window
driver.findElement(By.name("firstname")).sendKeys("parent window");
// Element on which to right click(Partial Link Test)
WebElement we = driver.findElement(By
.xpath("//a[contains(@title,'Form')]"));
Actions act = new Actions(driver);
// Right click,and click on second option from menu,which will open new
// window which is the child window
act.contextClick(we).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build()
.perform();
Thread.sleep(2000l);
Set<String> st = driver.getWindowHandles();
Iterator<String> itr = st.iterator();
String parentHandle = itr.next();
String childHandle = itr.next();
//Switching control to child window using its handle
driver.switchTo().window(childHandle);
// Control has been passed to child window, performing some action in
// the child window
driver.findElement(By.name("firstname")).sendKeys("child window");
Thread.sleep(2000l);
// This will close only the child window
//If we use driver.quit() instead, then the session gets closed right away
driver.quit();
// Shifting control back to parent window
driver.switchTo().window(parentHandle);
driver.findElement(By.name("lastname")).sendKeys(
"back in parent window");
Thread.sleep(1000l);
// This will close the session
driver.quit();
}
}
Pay It Forward
DR
No comments:
Post a Comment