Your ultimate guide

Browser Windows Handling Using Selenium with Java


Window Handling:
    Window handling in Selenium refers to the process of interacting with multiple browser windows or tabs when automating web applications. Selenium provides methods and techniques to switch between different browser windows or tabs and perform actions on elements within each window.

Here are the Selenium methods to handle windows/tabs:
  1. switchTo().window()
  2. getWindowHandle()
  3. getWindowHandles()




switchTo():
    In Selenium, 'switchTo' is a method provided by the WebDirver API that allows you to switch the focus of WebDirver to different contexts within a web page. It is primarily used for switching between different frames, alerts, windows, or browser tabs when automating web applications.



switchTo().window():
    We can use this method to switch different browser windows or tabs by using its index number or window address.

Syntax(index): driver.switchTo().window("index");
Syntax(window address): driver.switchTo().window(address




getWindowHandle( ): 
    Each browser window has a specific address and it changes dynamically when the browser is opened, The WindowHandle() method gets the address of the active browser window and it has the return type as String.

Syntax: String currentWindow = driver.getWindowHandle();



getWindowHandles( ): 
    getWindowHandles gets the address of all the browser windows and it has the return of Set.

Syntax: Set<String> allWindows = driver.getWindowHandles();



  • Example Program:
  1. package Selinium_demo;
  2. import java.util.ArrayList;
  3. import org.openqa.selenium.By;
  4. import org.openqa.selenium.WebDriver;
  5. import org.openqa.selenium.chrome.ChromeDriver;

  6. public class WindowHandler2 {
  7.    public static void main(String[] args) {
  8.       WebDriver driver = new ChromeDriver();
  9.       driver.get("https://testingcolleges.blogspot.com/p/windowhandlingdemo1.html");
  10.       driver.findElement(By.xpath("//*[@id='post-body-8403560454683602685']/button")).click();

  11.       //getting all windows data into one ArrayList variable(win)
  12.       ArrayList<String> win = new ArrayList<String> (driver.getWindowHandles());
  13.       //Switching to 3rd window(index=2)
  14.       driver.switchTo().window(win.get(2));
  15.    }
  16. }




To print the Address of the browser windows:

// To print the unique ID of the current window

System.out.println(driver.getWindowHandle());

// To print the unique ID of all windows

System.out.println(driver.getWindowHandles());



To close all browser windows one by one:

ArrayList<String> win = new ArrayList<String> (driver.getWindowHandles());

// To Close all windows except 1st window(Index=0)

for(int i=1;i<=win.size();i++){

driver.switchTo().window(win.get(i));

driver.close();

}

- Next Page: Handling Alerts

No comments:

Post a Comment