How To Handle Windows Using Selenium Java?

Timothy Joseph | October 31, 2022

How To Handle Window Using Selenium Java?

Selenium provides multiple ways to handle Windows or Tabs in a web application, and the most commonly used ways in any professional automation framework are as follows:

  • Method 1:
    Default Window Handle Procedure:- Selenium provides various methods to switch between multiple windows and perform required operations.

    Below is the code snippet showing switching and handling multiple windows:

    //Open Application
    driver.get("https://qasource.com//");

    // Returns parent window name
    String winOriginal =driver.getWindowHandle();
    Set<String> winHandles = driver.getWindowHandles();

    // Now iterate using Iterator
    Iterator<String> iteratorIt = winHandles.iterator();

    while(iteratorIt.hasNext())
    {
    String winNew=iteratorIt.next();
    if(!winOriginal.equals(winNew))
    {
    driver.switchTo().window(winNew);
    System.out.println(driver.switchTo().window(winNew).getTitle());
    }
    }
    //switch to the original window
    driver.switchTo().window(winOriginal);
    driver.close();

  • Method 2: Open duplicate tabs using Javascript executor. Below is the sample code snippet:

    String script = String.format("window.open('%s');", "view");
    ((JavascriptExecutor) driver).executeScript(script);

  • Method 3: Use the action class to open a new window. Shown below is a sample corresponding code snippet:

    WebElement element = driver.findElement(By.xpath("Your Web Element !!"));
    Actions actionElement = new Actions(driver);
    actionElement.keyDown(Keys.SHIFT).click(element).keyUp(Keys.SHIFT).build().perform();

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment

Categories