
Photo by Andrey Kwin
| Photo by Andrey Kwin |
Handling Multiple Tabs/Windows In Selenium WebDriver
In real-time scenarios, we come across a few challenges when we click on a web element in the webpage and if it redirects to a new web page /
new tab still the driver focus will remain on main page where we have clicked
the web element from.
In order to move focus on this newly
opened window/tab, we use Window Handles and switch to the window.
Below are methods in the selenium web driver to
handle newly opened windows/tabs.
driver.getWindowHandles()
will return the id of the window which is in string format and each
window has a unique id.
driver.getWindowHandle()
This will return
the id of the window which is in focus currently.
Below is an example of handling new windows/tab using 'driver.getWindowHandles()'
In the below example we are switching driver
focus to the window whose title matches with the title mentioned in our
condition and closing it.
Below is example of handling new
windows/tab using driver.getWindowHandle():
// Solution.java
public class PrimeExample {
public static void main(String args[]) {
int i, m = 0, flag = 0;
int n = 3; //it is the number to be checked
m = n / 2;
if (n == 0 || n == 1) {
System.out.println(n + " is not prime number");
} else {
for (i = 2; i <= m; i++) {
if (n % i == 0) {
System.out.println(n + " is not prime number");
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(n + " is prime number");
}
} //end of else
}
}
In below example, we are closing the parent
window using the parent window id
System.setProperty("webdriver.chrome.driver","Chrome driver path");
WebDriver driver=new ChromeDriver();
driver.get("http://demo.guru99.com/popup.php");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();
// will return the id of the window where the driver focus is on.
String MainPage=driver.getWindowHandle();
Set s = driver.getWindowHandles();
for(String i: s){
if(i.equals(MainPage)
{
driver.close();}
}