Search code examples
seleniumrandomselenium-webdriverpopupwindow

Selenium : Handle a window that popups up randomly


We have a feature that collects customer feedback. For this , when the user logs out , a window pops up up randomly - not every time for every customer. I want to handle this in my automation code.

Currently, at the log out, I'm expecting a window and switching to it and that code is failing when the popup window doesn't show up.

What's the best way to handle this .

This is what I have so far ...

    public static void waitForNumberOfWindowsToEqual(final int numberOfWindows) {


    ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return (driver.getWindowHandles().size() == numberOfWindows);
        }
    };

    WebDriverWait wait = new WebDriverWait(driver, BrowserFactory.explicitWait);


    wait.until(expectation);
}

Solution

  • I would handle the absence of popup window with a try/catch. Here is an example:

    try {
        WebDriverWait winwait = new WebDriverWait(driver, 3);
        String mainWindow = driver.getWindowHandle();
    
        // wait for 2 windows and get the handles
        Set<String> handles = winwait.until((WebDriver drv) -> {
            Set<String> items = drv.getWindowHandles();
            return items.size() == 2 ? items : null;
        });
    
        // set the context on the last opened window
        handles.remove(mainWindow);
        driver.switchTo().window(handles.iterator().next());
    
        // close the window
        driver.close();
    
        // set the context back to the main window
        driver.switchTo().window(mainWindow);
    
    } catch (TimeoutException ex) {
        System.out.println("No window present within 3 seconds");
    }