Protected by Copyscape
Powered By Blogger

Saturday, March 27, 2021

How to switch from one window to another using Selenium Java?

The task is very simple if you want to Switch from one window to another using WebDriver object of Selenium API. One has to extract the window id using the following statements

WebDriver driver;

driver=new ChromeDriver();

driver.get("https://www.google.co.in");

String winID=driver.getWindowHandle();

So, driver.getWindowHandle() is the statement where we are extracting the window id using getWindowHandle() method. Simmilarly, if we have multiple Window Ids then we can use the following statement to switch to another window.

driver.switchTo.window(windowid);

Please use the following example to get more information it.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class WinHdles {
static WebDriver driver;

public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "C:\\Browser Executables\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.get("https://opensource-demo.orangehrmlive.com/");

// now we will get the window id by using the below statement
String winID = driver.getWindowHandle();
System.out.println("Current window id is :" + winID);

WebElement lnk = driver.findElement(By.xpath("//*[text()='OrangeHRM, Inc']"));
lnk.click();

//Now after perform click on the above link the new browser window will be opened.
// So, now we will be having multiple windows ids

Set<String> winids = driver.getWindowHandles();

Iterator iterator = winids.iterator();

String strParentWinID = (String) iterator.next();
String strChildWinID = (String) iterator.next();

System.out.println("Parent Window ID is :" + strParentWinID);
System.out.println("Parent Window ID is :" + strChildWinID);

driver.switchTo().window(strChildWinID);
driver.findElement(By.xpath("//*[text()='Contact Sales']")).click();

driver.switchTo().window(strParentWinID);
driver.findElement(By.xpath("//*[@id='txtUsername']")).sendKeys("Admin");
        driver.close();
}
}


***********************************************************************************************************************************************************

I will be adding more concepts in my upcoming posts. Please keep me posted if you have any questions and concerns.



Best of Luck.
 

No comments: