- switchTo().window()
- getWindowHandle()
- getWindowHandles()
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");
- Example Program:
- package Selinium_demo;
- import java.util.ArrayList;
- import org.openqa.selenium.By;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.chrome.ChromeDriver;
-
- public class WindowHandler2 {
- public static void main(String[] args) {
- WebDriver driver = new ChromeDriver();
- driver.get("https://testingcolleges.blogspot.com/p/windowhandlingdemo1.html");
- driver.findElement(By.xpath("//*[@id='post-body-8403560454683602685']/button")).click();
-
- //getting all windows data into one ArrayList variable(win)
- ArrayList<String> win = new ArrayList<String> (driver.getWindowHandles());
- //Switching to 3rd window(index=2)
- driver.switchTo().window(win.get(2));
- }
- }
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();
}
No comments:
Post a Comment