Search code examples
javaseleniumxpathcss-selectorswebdriverwait

How to handle pop up windows Java Selenium?


For example, TjMaxx

When the user navigates for the first time pop up window shows up, sometimes 2, and it's hard to catch and move on. I tried try catch, but it does not work, because it opens some windows that I cannot see. How to catch all windows and dismiss them all for the guest user?

 try {
        WebElement closeWindowPromo = driver.findElement(By.xpath
                ("//div[@class =\"bx-row bx-row-submit bx-row-submit-no  bx-row-2uaILGf bx-element-1360650-2uaILGf\"]//button[@data-click = 'close']"));
        WebDriverWait w = new WebDriverWait(driver, 5);
        w.until(ExpectedConditions.visibilityOfElementLocated((By) closeWindowPromo));
        System.out.println("Element is visible");

    } catch (NoSuchElementException n) {

        System.out.println("Element is invisible");
    }
    wait = new WebDriverWait(driver, 10);

Solution

  • Instead of clicking on the close button try to click on the element with text as I don't want free shipping inducing WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

    • cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div[class*='bx-row-submit-no'] > button.bx-button[data-click = 'close'][type='reset']"))).click();
      
    • xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='bx-button' and @data-click = 'close'][@type='reset' and contains(., 'shipping')]"))).click();