Method and Description:
- getWindowHandle
()
- Return an opaque handle to this window that uniquely identifies it within this driver instance. - getWindowHandles
()
- Return a set of window handles which can be used to iterate over all open windows of this WebDriver instance by passing them toswitchTo()
.WebDriver.Options.window()
Example:
- Below example opens a page of w3schools.com
- And then clicks on ‘Try it yourself »’ link, which opens a new window.
- Switch to new window, perform some actions on it and then switch back to previous window
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.tests; | |
import java.util.concurrent.TimeUnit; | |
import org.openqa.selenium.By; | |
import org.openqa.selenium.WebDriver; | |
import org.openqa.selenium.firefox.FirefoxDriver; | |
import org.testng.annotations.AfterSuite; | |
import org.testng.annotations.BeforeSuite; | |
import org.testng.annotations.Test; | |
public class ChangeWindowFocusExample { | |
private WebDriver driver; | |
@BeforeSuite | |
public void setUp() throws Exception { | |
driver = new FirefoxDriver(); | |
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); | |
} | |
@AfterSuite | |
public void tearDown() throws Exception { | |
driver.quit(); | |
} | |
@Test | |
public void testMethod() throws Exception { | |
driver.get("http://www.w3schools.com/html/default.asp"); | |
// get an opaque handle to current window that uniquely identifies it within this driver instance. | |
String currentwindow = driver.getWindowHandle(); | |
//click on Try it yourself » link, it will open in new window | |
driver.findElement(By.xpath("//a[contains(@class,'tryitbtn')]")).click(); | |
//Now we have multiple windows, so get all windows handler and switch focus to non current window | |
for (String windownHandler : driver.getWindowHandles()) { | |
if (!windownHandler.equals(currentwindow)) | |
System.out.println("Switching to new window: " + windownHandler); | |
//switch to new window | |
driver.switchTo().window(windownHandler); | |
} | |
//maximize the new window to verify focus | |
driver.manage().window().maximize(); | |
//open any url | |
driver.get("http://www.google.com/"); | |
//close current window | |
driver.close(); | |
//switch to previous window | |
driver.switchTo().window(currentwindow); | |
//open any url to verify focus | |
driver.get("http://www.w3schools.com/"); | |
} | |
} |
No comments:
Post a Comment