Learn Selenium
上QQ阅读APP看书,第一时间看更新

Switching among windows

First, we will see a code example for handling multiple windows. For this chapter, there is an HTML file provided with this book named Window.html. It is a very basic web page that links to Google's search page. When you click on the link, the Google's search page is opened in a different window. Every time you open a web page using WebDriver in a browser window, WebDriver assigns a window handle to that. WebDriver uses the window handle to identify the window. At this point, in WebDriver, there are two window handles registered. Now, on the screen, you can see that the Google's search page is in the front and has the focus. At this point, if you want to switch to the first browser window, you can use WebDriver's switchTo() method to do that.

The API syntax for TargetLocator is as follows:

WebDriver.TargetLocator switchTo()

This method returns the WebDriver.TargetLocator instance, where you can tell the WebDriver whether to switch between browser windows or frames. Let's see how WebDriver deals with this:

public class WindowHandlingTest {

WebDriver driver;

@BeforeMethod
public void setup() throws IOException {
System.setProperty("webdriver.chrome.driver",
"./src/test/resources/drivers/chromedriver");
driver = new ChromeDriver();
driver.get("http://guidebook.seleniumacademy.com/Window.html");
}

@Test
public void handleWindow() {

String firstWindow = driver.getWindowHandle();
System.out.println("First Window Handle is: " + firstWindow);

WebElement link = driver.findElement(By.linkText("Google Search"));
link.click();

String secondWindow = driver.getWindowHandle();
System.out.println("Second Window Handle is: " + secondWindow);
System.out.println("Number of Window Handles so for: "
+ driver.getWindowHandles().size());

driver.switchTo().window(firstWindow);
}

@AfterMethod
public void tearDown() {
driver.quit();
}
}

Observe the following line in the preceding code:

String firstWindow = driver.getWindowHandle();

Here, the driver returns the assigned identifier for the window. Now, before we move on to a different window, it is better to store this value so that if we want to switch back to this window, we can use this handle or identifier. To retrieve all the window handles that are registered with your driver so far, you can use the following method:

driver.getWindowHandles()

This will return the set of identifiers of all of the browser window handles opened in the driver session so far. Now, in our example, after we open Google's search page, the window corresponding to it is shown in front with the focus. If you want to go back to the first window, you have to use the following code:

driver.switchTo().window(firstWindow);

This will bring the first window into focus.