Search code examples
javaselenium-webdriverpopuppopupwindow

How to handle Pop-up in Selenium WebDriver using Java


I want to handle sign-in part in rediff.com, but the below code doesn't work for that:

driver.get("http://www.rediff.com/");
WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
sign.click();
String myWindowHandle = driver.getWindowHandle();
driver.switchTo().window(myWindowHandle);
WebElement email_id= driver.findElement(By.xpath("//*[@id='signin_info']/a[1]"));
email_id.sendKeys("hi");

If myWindowHandle is not the correct string, then let me know how to get the pop-up Window name, because I can't find the name of the pop-up window.


Solution

  • To switch to a popup window, you need to use getWindowHandles() and iterate through them.

    In your code you are using getWindowHandle() which will give you the parent window itself.

    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); // switch to popup window
    
    // Now you are in the popup window, perform necessary actions here
    
    driver.switchTo().window(parentWindowHandler);  // switch back to parent window