简体   繁体   中英

How to switch back to parent window in Selenium WebDriver?

I need to close a child window and switch back to the parent window to perform some operations.

public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://www.example.com/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testUntitled2() throws Exception {
    driver.get(baseUrl + "/info.php");
    driver.findElement(By.cssSelector("i.fa.fa-facebook-sq")).click();
    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
    }

    // Perform the actions on new window
    driver.close(); // This will close new opened window

    //driver.switchTo().window(winHandleBefore); // I need to perform below

    driver.findElement(By.cssSelector("i.fa.fa-twitter-square")).click();
    driver.findElement(By.cssSelector("i.fa.fa-google-plus-  squ)).click();
    driver.findElement(By.cssSelector("i.fa.fa-linkedin-square")).click();
}

you can use this code for switching to child window and then back to parent window.

Code:

   String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
            String subWindowHandler = null;

            Set<String> handles = driver.getWindowHandles(); // get all window handles
            Iterator<String> iterator = handles.iterator();
            while (iterator.hasNext()){
                subWindowHandler = iterator.next();
            }
            driver.switchTo().window(subWindowHandler); 

*****perform operations on child window******************

driver.switchTo().window(parentWindowHandler);

I hope this will solve your problem

Create one parentWindowHandle String variable before for loop and store windowhandle there. Once you are done with your operation with child window, go back to that parentWindowHandle .

String parentWindowHandle = driver.getWindowHandle();
/* You code to move to child window*/

//After you done with child window
driver.switchTo().window(parentWindowHandle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM