Wednesday, April 8, 2015

WebDriver - Switch to a New Window

WebDriver - Switch to a New Window

Here you will learn how to switch to new window, switch to new browser or switch from child to parent window and more using Selenium WebDriver.

Following is a short snippet of code taken from Selenium Testing Tools Cookbook by Unmesh Gundecha. This code helps in identifying and handling a window by its name.
//Let's implement a test that identifies a pop-up window using its name attribute as follows: 
public void testWindowPopup() 
{ 
//Save the WindowHandle of Parent Browser Window 
String parentWindowId = driver.getWindowHandle();

//Clicking Help Button will open Help Page in new Popup Browser Window 
WebElement helpButton = driver.findElement(By.id("helpbutton")); 
helpButton.click();

try 
{ 
//Switch to the Help Popup Browser Window 
driver.switchTo().window("HelpWindow"); 
} 
catch (NoSuchWindowException e) 
{ 
e.printStackTrace(); 
}

//Verify the driver context is in Help Popup Browser Window 
assertTrue(driver.getTitle().equals("Help"));

//Close the Help Popup Window 
driver.close();

//Move back to the Parent Browser Window 
driver.switchTo().window(parentWindowId);

//Verify the driver context is in Parent Browser Window 
assertTrue(driver.getTitle().equals("Build my Car - Configuration")); 
}

Some of the links to help you with tasks like switch to new window, switch to new browser, switch from child to parent window and much more using Selenium WebDriver:

1. WebDriver switch to new browser opened after click on button. [Link]
2. How can I switch WebDriver control to new window? [Link]
3. How can I switch to new window using WebDriver? [Link]
4. How to handle the new window in selenium WebDriver? [Link]
5. Road to switch window in WebDriver. [Link]
6. WebDriver, CSharp, C# - Cannot switch between windows. [Link]
7. Selenium WebDriver in C#: Switch to new window or tab. [Link]
8. How to switch between two windows in browser using Selenium java. [Link]
9. How to Handle Alerts/Popups in Selenium WebDriver – Selenium Tutorial #16. [Link]
10. Switching to new window and again come to same window in java (Selenium WebDriver). [Link]
11. Switch between two browser windows using selenium WebDriver. [Link]
12. Selenium WebDriver using switch_to_windows() and printing the title doesn't print the title. [Link]
13. Switch from child to parent window in Selenium WebDriver. [Link]
14. How to switch control from child window to parent window in selenium WebDriver? [Link]
15. How To Work with Multiple Windows. [Link]